Linux & Terminal52 entries

Bash Scripting

Variables, loops, conditionals, functions, and scripting patterns for Bash shell

1Variables & Strings

NAME="value"
Assign variable (no spaces around =)
$NAME or ${NAME}
Reference variable
"Hello $NAME"
String with variable interpolation
'Hello $NAME'
Literal string (no interpolation)
${#STR}
String length
${STR:0:5}
Substring (offset:length)
${STR/old/new}
Replace first occurrence
${STR//old/new}
Replace all occurrences
${STR^^}
Uppercase entire string
${STR,,}
Lowercase entire string

2Conditionals

if [ condition ]; then ... fi
Basic if statement
if [[ $a == $b ]]; then ...
Extended test (preferred)
-eq -ne -lt -gt -le -ge
Numeric comparisons
== !=
String comparisons (inside [[ ]])
-z "$STR"
True if string is empty
-n "$STR"
True if string is non-empty
-f <file>
True if file exists and is regular
-d <dir>
True if directory exists
-e <path>
True if path exists (file or dir)
&& ||
Logical AND / OR

3Loops

for i in 1 2 3; do ... done
For loop over list
for i in {1..10}; do ... done
For loop with range
for f in *.txt; do ... done
For loop over files (glob)
for ((i=0; i<10; i++)); do ...
C-style for loop
while [ condition ]; do ... done
While loop
while read -r line; do ... done < file
Read file line by line
break
Exit loop
continue
Skip to next iteration

4Functions

function name() { ... }
Define a function
name() { ... }
Define function (shorthand)
$1 $2 $3
Function arguments (positional)
$#
Number of arguments
$@
All arguments as separate words
$?
Exit status of last command
return <n>
Return exit code from function
local var="value"
Local variable in function

5Input/Output & Redirection

echo "text"
Print text to stdout
printf "%s\n" "text"
Formatted output
read -p "Prompt: " VAR
Read user input into variable
cmd > file
Redirect stdout to file (overwrite)
cmd >> file
Redirect stdout to file (append)
cmd 2> file
Redirect stderr to file
cmd &> file
Redirect both stdout and stderr
cmd1 | cmd2
Pipe stdout of cmd1 to cmd2
cmd < file
Redirect file as stdin

6Special Variables

$0
Script name
$$
Current process ID (PID)
$!
PID of last background process
$?
Exit status of last command
$_
Last argument of previous command
RANDOM
Random number (0-32767)
SECONDS
Seconds since script started