Bash variables: Difference between revisions

From wikinotes
No edit summary
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>

Revision as of 15:55, 7 August 2021

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 -n 1 input  # user input to $input

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.