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

血红的双手。 提交于 2021-02-19 07:23:12

问题


I thought C shell script will behave 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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/3694163/do-we-have-short-circuit-logical-operators-in-c-shell-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!