Bash variables: Difference between revisions
From wikinotes
Line 23: | Line 23: | ||
FOO=${VARIABLE:=default} # FOO=$VARIABLE if exists, otherwise "default" | FOO=${VARIABLE:=default} # FOO=$VARIABLE if exists, otherwise "default" | ||
read -n 1 input | 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 | vared -p 'Do thing? (y/n): ' -c reply # (zsh+zle) save input to $reply | ||
</source> | </source> |
Latest revision as of 17:10, 13 March 2022
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'
Assignment
var="var" 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
.