Skip to content

Latest commit

 

History

History
102 lines (64 loc) · 3.77 KB

bash-scripting.md

File metadata and controls

102 lines (64 loc) · 3.77 KB

Bash Scripting

Resources

Tutorials/ Getting Started

Reference

Tips & Tricks

Talks

General Advice

bash is not sh

While bash is "sh-compatible" some features of bash will break or cause unexpected behaviour in sh.

Forget the .sh extension

Don't give scripts an .sh extension.

  1. The Google Shell Style Guide advises against it unless it's a library
  2. It's a bash script, not an sh script

Pipes

grep

If you're piping to grep multiple times only the last grep in the sequence can be called with -q.

Examples

Shebang

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
  1. Rational
    • "#!/usr/bin/env searches PATH for bash, and bash is not always in /bin, particularly on non-Linux systems."
  2. 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 Script

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.

Debug Mode

Print every command before its execution, replacing the variables with their real values.

set -x

The Set Builtin

Unofficial Strict Mode

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

Unofficial Bash Strict Mode