问题
I need to loop through a bunch of different scenarios (variable scen), but can't figure out how to use the if statements in the tcsh shell script. Getting the error "if: Expression Syntax" Can someone please tell me what I have wrong? Simplified code follows! Thanks!
#!/bin/tcsh -f
#
set val = 0
foreach scen ( a b )
echo $scen
if ($scen==a) then
echo $scen
else
echo $val
endif
end
回答1:
Solution to your problem
Apparently you need spaces around the equality comparison ==
. This
works:
#!/bin/tcsh -f
#
set val = 0
foreach scen ( a b )
echo $scen
if ($scen == a) then
echo $scen
else
echo $val
endif
end
producing:
a
a
b
0
Unsolicited advice
Also, unless you have to be using tcsh here, I suggest using a better shell like bash or zsh. Here are some arguments against csh and tcsh:
- http://www.shlomifish.org/open-source/anti/csh/
- http://www.faqs.org/faqs/unix-faq/shell/csh-whynot/
For comparison, here's your code in bash (and zsh):
#!/bin/bash
# No space around equal sign in assignment!
val=0
for scen in a b; do
echo $scen
if [[ $scen == a ]]; then
echo $scen
else
echo $val
fi
done
There's no important difference here, but see the above articles for examples where csh would be a bad choice.
来源:https://stackoverflow.com/questions/19799021/tcsh-script-if-statement