Skip to content

Bash scripting

Turning command sequences into scripts: output and input, variables, conditions, loops and functions, plus the tools that make scripts robust and safe to run unattended.

Basics: How a script is built: shebang, quoting, variables, arguments and exit codes

Output and input

  • echo


    Print text and variables.

  • printf


    Formatted output: columns, numbers.

  • read


    Read input and files line by line.

Variables and environment

  • export


    Pass variables on to child processes.

  • source


    Load a file into the current shell.

Conditions

  • test


    Check files, strings and numbers.

  • if


    Run commands only if a condition is true.

  • case


    Choose by pattern.

Loops

  • for


    Repeat for every element of a list.

  • while


    Repeat while a condition holds.

Functions and exit codes

  • function


    Named blocks of commands.

  • exit


    End a script with an exit code.

Robust scripts

  • set


    Stop on errors, debug scripts.

  • trap


    Clean up on exit and signals.

  • getopts


    Read options like -v and -t.

  • shellcheck


    Find mistakes before the script runs.