- shellscript.sh "shell scripting tutorial"
- Linux Documentation Project - Bash Guide for Beginners
- BashGuide "aid people interested in learning to work with BASH"
- Serious Shell Programming
- GNU Bash Reference Manual
- Cheatsheet devhints.io
- Bash Hackers Wiki
- Shell Scripts Matter "a summary of everything that can, and should be done when writing shell scripts."
- ShellCheck "static analysis tool for shell scripts"
- Unofficial Bash Strict Mode "causes bash to behave in a way that makes many classes of subtle bugs impossible."
- Google Shell Style Guide
While bash
is "sh-compatible" some features of bash
will break or cause unexpected behaviour in sh
.
- Read bash Is Not sh for a more detailed explanation.
Don't give scripts an .sh
extension.
- The Google Shell Style Guide advises against it unless it's a library
- It's a
bash
script, not ansh
script
If you're piping to grep
multiple times only the last grep
in the sequence can be called with -q
.
First line of the script that indicates which interpreter is used to execute the file. The #!
must be at the very start of the file, with no spaces or blank lines before it.
#!/usr/bin/env bash
- Rational
- "
#!/usr/bin/env
searchesPATH
forbash
, andbash
is not always in/bin
, particularly on non-Linux systems."
- "
- Rational
- "This way, you don't have to look for it in a specific place on the system, as those paths may be in different locations on different systems. As long as it's in your path, it will find it."
Execute bash
and tell it to read the script myscript
. When executing the script this way the shebang line (#!
) is just a comment, bash
does nothing with it
bash myscript
We can give the script executable permission. Instead of calling bash
manually, we can execute myscript
directly.
chmod +x myscript # Mark myscript as executable
./myscript # Directly execute myscript
When myscript
is executed this way, the shebang line (#!
) is used to determine which interpreter to use.
Print every command before its execution, replacing the variables with their real values.
set -x
set -euo pipefail
# -e: Exit if any command returns non-zero status code
# -u: Prevent using undefined variables
# -o pipefail: Force pipelines to fail on first non-zero status code