Bash variables: Difference between revisions
From wikinotes
(5 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
= Variable Scope = | |||
<blockquote> | |||
By default, variables are global and variables do not need to be declared.<br> | |||
You can declare local variables, or array types. | |||
<syntaxhighlight lang="bash"> | |||
declare foo # declare global variable '$foo' | |||
local foo # declare function-local variable '$foo' | |||
readonly foo # declare read-only variable '$foo' | |||
</syntaxhighlight> | |||
Each of these types can also define an array, or associative-array with <code>-a/-A</code>. | |||
<syntaxhighlight lang="bash"> | |||
local -a foo # declare local array '$foo' | |||
local -A foo # declare local associative-array '$foo' | |||
</syntaxhighlight> | |||
</blockquote><!-- Variable Scope --> | |||
= Assignment = | = Assignment = | ||
<blockquote> | <blockquote> | ||
<source lang="bash"> | <source lang="bash"> | ||
var="var" | var="var" | ||
FOO=${VARIABLE:=default} | 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 | |||
</source> | </source> | ||
</blockquote><!-- Assignment --> | </blockquote><!-- Assignment --> | ||
Line 10: | Line 31: | ||
<blockquote> | <blockquote> | ||
<source lang="bash"> | <source lang="bash"> | ||
test -z $var && echo "variable does not exist, or has no value" | test -z "$var" && echo "variable does not exist, or has no value" | ||
test -n $var && echo "variable exists and has a nonzero value" | test -n "$var" && echo "variable exists and has a nonzero value" | ||
</source> | </source> | ||
There are many more options. See <code>man test</code>. | There are many more options. See <code>man test</code>. | ||
</blockquote><!-- test variable --> | </blockquote><!-- test variable --> |
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
.