tags:

views:

116

answers:

4

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
+2  A: 

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
I agree that works in bash. Unfortunately I don't know bash.
Walter Nissen
+2  A: 
mustsucceed || exit 1
mustbeignored || :
Ignacio Vazquez-Abrams
This does not work for me. The script still stops.
Walter Nissen
@Walter, then you must not use `-e` when you invoke the shell.
glenn jackman
+1  A: 

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
Most of the time I care if it fails. For a few exceptional cases, I don't care.
Walter Nissen
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
+1  A: 

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