Bash Scripting

Script Basics

#!/bin/bashShebang (script interpreter)
chmod +x script.shMake script executable
./script.shRun script
source script.shRun in current shell
set -eExit on error
set -uError on undefined vars
set -xDebug: print commands
set -euo pipefailStrict mode (recommended)

Variables

VAR="value"Assign variable (no spaces!)
$VAR / ${VAR}Use variable value
${VAR:-default}Default if unset
${VAR:=default}Assign default if unset
${#VAR}Length of variable
${VAR/old/new}Replace first match
${VAR//old/new}Replace all matches
${VAR%suffix}Remove trailing suffix
${VAR#prefix}Remove leading prefix
readonly VAR="val"Constant variable
export VARExport to child processes
local VAR="val"Local to function

Arguments & Special Vars

$0Script name
$1 $2 ...Positional arguments
$#Number of arguments
$@All args (separate words)
$*All args (single string)
$?Last exit code
$$Current PID
$!Last background PID

Conditionals

if [ cond ]; then ... fiBasic if statement
if [[ cond ]]; thenExtended test (preferred)
elif [ cond ]; thenElse if branch
elseDefault branch
-eq -ne -lt -gt -le -geNumeric comparisons
== / !=String comparison
-z "$VAR"String is empty
-n "$VAR"String is not empty
-f fileFile exists (regular)
-d dirDirectory exists
-r / -w / -xReadable / writable / exec
&& / ||Logical AND / OR

Loops

for i in 1 2 3; do ... doneFor loop over list
for f in *.txt; doLoop over files
for ((i=0; i<10; i++)); doC-style for loop
while [ cond ]; do ... doneWhile loop
until [ cond ]; do ... doneUntil loop
while read line; doRead file line by line
break / continueExit / skip iteration
seq 1 10Generate number sequence

Functions

fn() { ... }Define function
function fn { ... }Alternative syntax
fn arg1 arg2Call with arguments
return 0Return exit code
local var="val"Local variable
result=$(fn)Capture function output

Arrays

arr=(a b c)Define array
${arr[0]}Access element
${arr[@]}All elements
${#arr[@]}Array length
arr+=(d)Append element
unset arr[1]Remove element
${arr[@]:1:2}Slice (offset:length)

I/O & Subshells

echo "text"Print to stdout
printf "%s\n" "$var"Formatted output
read -p "Prompt: " VARRead user input
read -sSilent input (password)
$(command)Command substitution
$((expr))Arithmetic expansion
cmd1 | cmd2Pipe output
cmd > file 2>&1Redirect all to file
here_doc <<EOFHere document
trap "cmd" EXITRun on script exit
allprintabledoc.com