POSIX shells
Tips
shell options
-e(errexit): exit immediately if any untested command fails.-u(nounset): Write a message to standard error when attempting to expand a variable that is not set.-v(verbose): The shell writes its input to standard error as it is read.-o pipefail(not POSIX compliant): Fail if any command in a pipeline fails, not just the last.-x(xtrace): Write each command to standard error (preceded by a ‘+ ’) before it is executed.
exit codes
To capture exit codes, use the following:
## 1. Run the date command ##
cmd="date"
$cmd
## 2. Get exist status and store into '$status' var ##
status=$?
To exit with exit code N, use exit N.
POSIX arithmetic expansion
### echo "$((...))", e.g.
$ echo "$((1 + 10))"
11
Only works for integers.
Particular shells
bash
ash
Portability
If you're planning to run a script on various systems with different shells you better abide by the POSIX standard in your script. This ensures that it works across different shells, i.e. is portable.
You can check for POSIX compliance by either running the
script in a POSIX compliant shell (like dash or bash --posix), or by
using shellcheck with shellcheck --shell=sh. If you only want to check
for bashisms, run checkbashisms on your script.