Log inSign up

Bash scripting guides

Scripts, variables, conditions, loops, arrays, functions, input and error handling. 10 guides in this topic.

Write and run a Bash script

Create a script file with a shebang line, make it executable with chmod, run it from any folder and check it with bash -n and shellcheck.

Bash variables and strings

Assign and quote variables correctly, use defaults, trim and replace text with parameter expansion, and do integer math without calling external tools.

if, else and case in Bash

Branch on exit codes, file tests, string and number comparisons with if, elif and else, match patterns with case and keep the logic readable.

for, while and until loops

Repeat work over lists, number ranges, files and command output with for, while and until, read lines safely, and control loops with break and continue.

Arrays in Bash

Store lists in indexed arrays and key value pairs in associative arrays, loop over them safely, fill them from files with mapfile and build command lines.

Functions in Bash

Group repeated steps into Bash functions, pass arguments, return status codes and values, keep variables local and share helpers across scripts.

Read user input in Bash

Ask questions with read, hide passwords, set timeouts and defaults, confirm risky steps, build menus with select and parse options with getopts.

Heredocs and writing to files

Write and append files from scripts with redirection, tee and heredocs, keep or expand variables on purpose, write root-owned files and replace files atomically.

Aliases and a tidy .bashrc

Create shortcuts with alias, keep them in a separate file loaded by .bashrc, improve history and the prompt, and know which startup file Bash reads when.

Error handling with set -euo pipefail

Stop scripts on the first failure with set -euo pipefail, report where it happened with an ERR trap, clean up temp files with an EXIT trap and retry flaky steps.