开发者

Do we have short circuit logical operators in C shell script?

I thought C shell script will be开发者_开发技巧have like C and use short circuit evaluation for logical operators.

if ((! -e $cache ) || ("`find $monitor -newer $cache`" != "")) then
...
endif

But in the if statement, even if the first condition is true, the second is checked giving me errors.

Do we have a short circuit logical OR in C shell script?


Yes, && and || are short-circuit operators in tcsh (just as they are in C). And there are two distinct forms, one that works on commands (as in false && echo foo), and one that works on expression (as in if (-e $file1 && -e $file2)).

I'm not entirely sure what's going on here, except that csh and tcsh are notorious for ill-defined syntax. A bit of experimentation shows that saving the output of find in a variable avoids the error:

set s = "`find $monitor -newer $cache`"
if ((! -e $cache) || ("$s" != "")) then
    echo ok
endif

(Note that the extra parentheses aren't really necessary, but they don't hurt anything.)

But more improvement is possible. Storing the entire output of the find command in a variable isn't really necessary. Instead, you can invoke find and use its returned status to tell you whether it found anything:

I just tried this:

if (! -e $cache || { find $monitor -newer $cache >& /dev/null } ) then
    echo ok
endif

and it worked -- except that the >& /dev/null redirection seems to be ignored within the braces.

Instead, you can execute the "find" command separately, and then examine the resulting $status. Which means that you lose the benefit of the short-circuit || operator; you'll have to resort to nested if statements and/or temporary variables.

Perhaps the real lesson is this: I've been using csh and tcsh for more years than I care to admit, and the only way I was able to figure out a lot of this stuff was by trial and error. You can do this using tcsh or csh, but you're probably better of using a different scripting language. For example, in Bourne shell, this is fairly straightforward:

if [ ! -e $cache ] || find $monitor -newer $cache >/dev/null 2>&1 ; then
    ...
fi


Usually, &&and || are short-circut. Consider something like this:

$ false && echo foo
$ true || echo foo

In both cases, foo won't be put out.

But, AFAIK you cannot use this kind of string comparison like this, even if short-circuit, csh will still syntax-check the whole thing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜