Bash Scripting
Script Basics
#!/bin/bash—Shebang (script interpreter)
chmod +x script.sh—Make script executable
./script.sh—Run script
source script.sh—Run in current shell
set -e—Exit on error
set -u—Error on undefined vars
set -x—Debug: print commands
set -euo pipefail—Strict 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 VAR—Export to child processes
local VAR="val"—Local to function
Arguments & Special Vars
$0—Script 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 ... fi—Basic if statement
if [[ cond ]]; then—Extended test (preferred)
elif [ cond ]; then—Else if branch
else—Default branch
-eq -ne -lt -gt -le -ge—Numeric comparisons
== / !=—String comparison
-z "$VAR"—String is empty
-n "$VAR"—String is not empty
-f file—File exists (regular)
-d dir—Directory exists
-r / -w / -x—Readable / writable / exec
&& / ||—Logical AND / OR
Loops
for i in 1 2 3; do ... done—For loop over list
for f in *.txt; do—Loop over files
for ((i=0; i<10; i++)); do—C-style for loop
while [ cond ]; do ... done—While loop
until [ cond ]; do ... done—Until loop
while read line; do—Read file line by line
break / continue—Exit / skip iteration
seq 1 10—Generate number sequence
Functions
fn() { ... }—Define function
function fn { ... }—Alternative syntax
fn arg1 arg2—Call with arguments
return 0—Return 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: " VAR—Read user input
read -s—Silent input (password)
$(command)—Command substitution
$((expr))—Arithmetic expansion
cmd1 | cmd2—Pipe output
cmd > file 2>&1—Redirect all to file
here_doc <<EOF—Here document
trap "cmd" EXIT—Run on script exit
allprintabledoc.com