I want to let my script exit with a message when a cd command fails. I tried that by do the following:
cd $foo || echo "Error xyz"; exit 1
However, exit gets called regardless of the cd's success. When I type the following, it does not work either, because exit only exits the subshell:
cd $foo || ( echo "Error xyz"; exit 1 )
How can I achieve the desired behaviour without defining a function? Of course I could just compare $(pwd) with $foo, but that could lead to problems regarding symlinks and stuff.
The echo command is used to display the exit code for the last executed Fault Management command.
Exit When Any Command Fails This can actually be done with a single line using the set builtin command with the -e option. Putting this at the top of a bash script will cause the script to exit if any commands return a non-zero exit code.
Exit code 2 signifies invalid usage of some shell built-in command. Examples of built-in commands include alias, echo, and printf.
pipefail. If set, the return value of a pipeline is the value of the last (rightmost) command to exit with a non-zero status, or zero if all commands in the pipeline exit successfully. This option is disabled by default.
You can use the { list; }
compound command. The list of commands is executed in the current shell context:
cd "$foo" || { echo "Error xyz"; exit 1; }
(Note the trailing semicolon or newline is required.)
The most common definition of functions in bash
usually uses exactly this compound command for the "function body":
f() { list; }
although, bash
functions can be defined with any compound command for their body, for example:
f() ( list; )
f() (( $1 > 10 ))
f() [[ $1 != "test" ]]
even:
f() for i in {1..10}; do echo $i; done
f() case ... esac
You can just use an if statement. It is more readable in most cases, especially if you want to craft a proper error message:
if ! cd "${dir}" ; then
echo "Failed to enter folder ${dir}"
echo "Aborting"
exit 1
fi
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With