Bash variables

From wikinotes

Variable Scope

By default, variables are global and variables do not need to be declared.
You can declare local variables, or array types.

declare  foo  # declare global variable '$foo'
local    foo  # declare function-local variable '$foo'
readonly foo  # declare read-only variable '$foo'

Each of these types can also define an array, or associative-array with -a/-A.

local -a foo  # declare local array '$foo'
local -A foo  # declare local associative-array '$foo'


FOO=${VARIABLE:=default}  # FOO=$VARIABLE if exists, otherwise "default"

read -p 'Do thing? (y/n): ' -n 1 input # (bash) read 1 char, save to $input
vared -p 'Do thing? (y/n): ' -c reply  # (zsh+zle) save input to $reply

test variable

test -z "$var" && echo "variable does not exist, or has no value"
test -n "$var" && echo "variable exists and has a nonzero value"

There are many more options. See man test.