Variables
Assign without spaces
No spaces around =. Quote expansions when the value might contain whitespace.
name="Ada Lovelace"
echo "$name"
Environment vs shell
export makes a variable available to child processes.
export GREETING="Hello"
bash -c 'echo "$GREETING"'
Defaults and lengths
Parameter expansion covers common cases without if.
user="${1:-friend}"
echo "Hi, $user"
echo "Length: ${#user}"
Readonly and locals
Use readonly for constants. Inside functions, prefer local so you do not clobber globals.
readonly APP_NAME=demo
myfn() { local x=1; echo "$x"; }
Comments
One comment per signed-in account. Comments are saved with this page’s URL.