tcsh script if statement

点点圈 提交于 2019-12-10 23:53:47

问题


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

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