Search code examples
shelltcsh

tcsh script if statement


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

Solution

  • 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:

    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.