The easiest way to do this is to use the -e
option in your shell. For example:
#!/bin/sh -e
command1
command2
In this script, if command1
fails, then the script as a whole will fail at that point without running any further commands.
Question
If i copy and paste all the commands into the terminal.. some do not even go through.
so the solution is perhaps to turn the file into an executable file and then execute it.
but what if some commands fail.
the script keeps on executing the other commands.
obviously there is no solution to this right ?
Solution
The easiest way to do this is to use the -e
option in your shell. For example:
#!/bin/sh -e
command1
command2
In this script, if command1
fails, then the script as a whole will fail at that point without running any further commands.
OTHER TIPS
You can check the error code from commands you run
#!/bin/bash
function test {
"$@"
status=$?
if [ $status -ne 0 ]; then
echo "error with $1"
exit 255
fi
return $status
}
test ls
test ps -ef
test not_a_command
taken from here for more information Checking Bash exit status of several commands efficiently
@Terminal, you were almost there.
If you just stick &&
on the end of each command, then execution will stop with the first failure (ie. the first command that returns a non-zero exit code).
Example:
#!/bin/sh
true &&
echo 'got here' &&
echo 'got here too' &&
false &&
echo 'also got here'
produces the output
got here
got here too
(Actually, I thought it would also require line-continuation markers too: && \
, but a quick test showed otherwise.)
Note: All of the above assumes that your shell is bash; I can't speak for other shells.