Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tcsh script if statement

Tags:

shell

tcsh

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
like image 816
user50679 Avatar asked Nov 05 '13 21:11

user50679


1 Answers

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.

like image 111
ntc2 Avatar answered Sep 25 '22 18:09

ntc2