Bash Scripting
Shebang
Variables
public_var="value"
local local_var="local_value" # local variable inside function
echo $public_var # access variable value
echo $0 # access script name
echo $1 # access first script argument
echo $@ # access all script arguments
echo $# # access number of script arguments
echo $$ # access current script PID
echo $? # access last command exit code
Arrays
Indexed
array=("value1" "value2" "value3")
echo ${array[0]} # access first element
echo ${array[@]} # access all elements
Associative
declare -A assoc_array=(
["key1"]="value1"
["key2"]="value2"
)
echo ${assoc_array["key1"]} # access value by key
echo ${!assoc_array[@]} # access all keys
echo ${assoc_array[@]} # access all values
Loops
Numeric (c-style) - fastest loop
Array
Infinite
If Statements
[ ] - POSIX test (portable, works in sh)
if [ "$var" -eq 5 ]; then
echo "Equal to 5"
fi
if [ "$str" = "hello" ]; then # use = not == for POSIX compliance
echo "Matched"
fi
[[ ]] - Bash extended test (recommended in bash scripts)
if [[ "$str" == "hello" ]]; then # no word splitting/globbing, supports pattern matching
echo "Matched"
fi
if [[ "$str" =~ ^[0-9]+$ ]]; then # regex matching
echo "Numeric"
fi
if [[ -f "$file" && -r "$file" ]]; then # && / || work directly inside [[ ]]
echo "File exists and is readable"
fi
(( )) - Arithmetic evaluation
if (( var == 5 )); then # C-style comparison, no $ needed on variables
echo "Equal to 5"
fi
if (( var > 0 && var < 10 )); then
echo "In range"
fi
test - Command form (identical to [ ])
Common test flags
-e file # exists
-f file # regular file
-d file # directory
-r file # readable
-w file # writable
-x file # executable
-z string # string is empty
-n string # string is non-empty
Short-circuit form (no if block)
[ -f file.txt ] && echo "exists" # runs on success
[ -f file.txt ] || echo "missing" # runs on failure
Exit Codes
0 = Match Found / Success
echo $?: 0
1 = No Match Found
echo $?: 1
2 = Syntax or File Error
echo $?: 2
Avoid Error Stopping Script Execution
option 1 (fastest):
option 2:
option 3:
option 4: