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> myfile
works 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"; fi
The
true
command:
always returns an exit code indicating success (for most shells this is0
), and thefalse
command always returns an exit code indicating failure (for most shells this is1
).Use
true
andfalse
to:
- 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
true
andfalse
using the longhand/bin/true
and/bin/false
if [ -t 1 ]; then
is_tty() {
/bin/true
}
else
is_tty() {
/bin/false
}
fi
The
-e
shell 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
bash
interpreter
bash -e myscript.sh
- in a script using the
set
builtin
#!/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 || :