You may find yourself needing to manipulate exit codes or how a script behaves with them.
Sometimes in shell programming doing nothing is very useful.
Use
:to:
- Force a command to never return an error such as when you want the output of an error but not the exit code that goes with it.
ssh user@${i} 'echo OK' || :;
- Create a file without running a program which is much faster than using
touch. Although for most shells> myfileworks just fine.
: > /path/to/file
- Leave a placeholder in a conditional for code you intend to write (not the best habit).
if validate_somthing; then :; else echo "validation error"; fiThe
truecommand:always returns an exit code indicating success (for most shells this is0), and thefalsecommand always returns an exit code indicating failure (for most shells this is1).Use
trueandfalseto:
- Simulate a boolean value by conditionally writing a function, such as as when you need to know if your script was run from a terminal or not.
if [ -t 1 ]; then
is_tty() {
true
}
else
is_tty() {
false
}
fi
- or be explicit and call
trueandfalseusing the longhand/bin/trueand/bin/false
if [ -t 1 ]; then
is_tty() {
/bin/true
}
else
is_tty() {
/bin/false
}
fiThe
-eshell option is used to force orce a script to exit whenever a command exits with a non zero exit code.Use
-e:
- with a shebang line
#!/bin/bash -e
- invoked through the
bashinterpreter
bash -e myscript.sh
- in a script using the
setbuiltin
#!/usr/bin/bash
cd .. || echo "could not move up a directory"
set -e
echo "the next command will fail" && /bin/false
echo "this line will never run"set -e
grep mypattern myfile || :