5

I've got a tcsh shell script that I would like to stop with an error on nonzero status most of the time, but in some cases I want to ignore it. For example:

#!/bin/tcsh -vxef

cp file/that/might/not/exist . #Want to ignore this status
cp file/that/might/not/exist . ; echo "this doesn't work"
cp file/that/must/exist . #Want to stop if this status is nonzero
Walter Nissen
  • 16,451
  • 4
  • 26
  • 27
  • 1
    csh programming considered harmful. seriously. http://www.faqs.org/faqs/unix-faq/shell/csh-whynot/ – msw Jun 15 '10 at 15:14
  • I'm looking at a similar issue. It seems that tcsh treats builtin commands (like cd and limit) differently than external commands (like false). Built in commands always cause the script to terminate regardless of -e. Also, "|| echo last command failed" doesn't work as expected. With -e the part after || is never called. Without -e the part after || is called as expected, but for a built in command you'll exit the script right after that. Yuck! – Trade-Ideas Philip Sep 27 '17 at 18:06

4 Answers4

3

I don't know about tcsh, but with bash, you can use set -e to do this. When the -e flag is set, bash will exit immediately if any subcommand fails (see the manual for technical details). When not set, it will continue to execute. So, you can do something like this:

set +e
cp file/that/might/not/exist .  # Script will keep going, despite error
set -e
cp file/that/might/not/exist .  # Script will exit here
echo "This line is not reached"
Adam Rosenfield
  • 390,455
  • 97
  • 512
  • 589
3

Here we go: Spawn a new shell, use ';' to ignore the first status, and it returns all clear.

$SHELL -c 'cp file/that/might/not/exist . ; echo "good"'
Walter Nissen
  • 16,451
  • 4
  • 26
  • 27
2
mustsucceed || exit 1
mustbeignored || :
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • 1
    @Walter, then you must not use `-e` when you invoke the shell. – glenn jackman Jun 15 '10 at 18:33
  • @glennjackman, as he stated at the top of the question, he "would like to stop with an error on nonzero status most of the time." That's why we're doing this with a '-e' context. – macetw May 04 '17 at 18:53
1

If you don't care if it fails, remove the -e from your shebang. @Adam's answer ought to have provided a hint to you if you had looked at the tcsh documentation.

Also, you can throw away the error message:

cp dont_care       . >& /dev/null
cp still_dont_care . >& /dev/null || echo "not there"
cp must_be_there   . >& /dev/null || exit 1 # oh noes!
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • 1
    Most of the time I care if it fails. For a few exceptional cases, I don't care. – Walter Nissen Jun 15 '10 at 18:29
  • 1
    As long as that `e` is there in `#!/bin/tcsh -vxef`, it will always exit on error; that's what the `e` does. You have to remove the `e` to get any other behavior. `` – frayser Sep 30 '10 at 05:00