Taken your word "every command depends on every previous command. If any command fails the entire script should fail" literally, i think you don't need any special function to treat the errors .
All you need is to chain your commands with &&
operator and ||
operator, which does exactly what you wrote.
For example this chain will broke and will print "something went wrong" if any of the previous commands broke (bash reads from left to right)
cd foo && rm a && cd bar && rm b || echo "something went wrong"
Real example (i created dir foo, file a, dir bar and file b just for a real demo):
gv@debian:/home/gv/Desktop/PythonTests$ cd foo && rm a && cd bar && rm bb || echo "something is wrong"
rm: cannot remove 'bb': No such file or directory
something is wrong #mind the error in the last command
gv@debian:/home/gv/Desktop/PythonTests$ cd foo && rm aa && cd bar && rm b || echo "something is wrong"
rm: cannot remove 'aa': No such file or directory
something is wrong #mind the error in second command in the row
And finally if all commands have been executed successfully (exit code 0), script just goes on :
gv@debian:/home/gv/Desktop/PythonTests$ cd foo && rm a && cd bar && rm b || echo "something is wrong"
gv@debian:/home/gv/Desktop/PythonTests/foo/bar$
# mind that the error message is not printed since all commands were successful.
What is important to remember is that with the use of && next command is executed if previous command exited with code 0 which for bash means success.
If any command goes wrong in the chain then the command / script / whatever follows || will be executed.
And just for the record, If you need to perform different actions depending on the command that broke , you could also do it with classic script by monitoring the value of $?
which reports the exit code of the exactly previous command (returns zero if command executed successfully or other positive number if command failed)
Example:
for comm in {"cd foo","rm a","cd bbar","rm b"};do #mind the error in third command
eval $comm
if [[ $? -ne 0 ]];then
echo "something is wrong in command $comm"
break
else
echo "command $comm executed succesful"
fi
done
Output:
command cd foo executed succesfull
command rm a executed succesfull
bash: cd: bbar: No such file or directory
something is wrong in command cd bbar
Tip : You can suppress the message "bash: cd: bbar: No such file..." by applying eval $comm 2>/dev/null