Bash Variables
Working with variables in Bash
Variable Declaration
name=value # assign variable (no spaces)
readonly name=value # read-only variable
declare -i num=10 # declare integer
declare -r name=value # read-only variable
Variable Usage
echo $name # access variable
echo ${name} # access variable (preferred)
echo ${name:-default} # default value if unset
echo ${name:=default} # assign default if unset
unset name # delete variable
Special Variables
$0 # script name
$1, $2, ... # positional parameters
$@ # all arguments as separate words
$* # all arguments as single word
$# # number of arguments
$$ # current process ID
$! # last background process ID
Environment Variables
export VAR=value # export to child processes
$HOME # user home directory
$PATH # executable search path
$USER # current user
$PWD # current directory
String Operations
${#name} # string length
${name:0:5} # substring from position 0, length 5
${name/old/new} # replace first occurrence
${name//old/new} # replace all occurrences
${name#pattern} # remove shortest match from start
${name%pattern} # remove shortest match from end