Exit tcsh script if error

前端 未结 1 858
生来不讨喜
生来不讨喜 2021-02-20 01:10

I am tryin to write a tcsh script. I need the script exit if any of its commands fails.

In shell I use set -e but I don\'t know its equivalent in tcsh

相关标签:
1条回答
  • 2021-02-20 02:01

    In (t)csh, set is used to define a variable; set foo = bar will assign the value bar to the variable foo (like foo=bar does in Bourne shell scripting).

    In any case, from tcsh(1):

    Argument list processing
       If the first argument (argument 0) to the shell is `-'  then  it  is  a
       login shell.  A login shell can be also specified by invoking the shell
       with the -l flag as the only argument.
    
       The rest of the flag arguments are interpreted as follows:
    
    [...]
    
       -e  The  shell  exits  if  any invoked command terminates abnormally or
           yields a non-zero exit status.
    

    So you need to invoke tcsh with the -e flag. Let's test it:

    % cat test.csh
    true
    false
    
    echo ":-)"
    
    % tcsh test.csh
    :-)
    
    % tcsh -e test.csh
    Exit 1
    

    There is no way to set this at runtime, like with sh's set -e, but you can add it to the hashbang:

    #!/bin/tcsh -fe
    false
    

    so it gets added automatically when you run ./test.csh, but this will not add it when you type csh test.csh, so my recommendation is to use something like a start.sh which will invoke the csh script:

    #!/bin/sh
    tcsh -ef realscript.csh
    
    0 讨论(0)
提交回复
热议问题