Declare (Bash)
The Bash command declare is similar to dim and set in some other language: To declare and maybe initialize a variable.
It can be ommitted for general variables, but is needed in specific cases, like for declaring a name reference, an indexed array or an associative array
$ help declare declare: declare [-aAfFgilnrtux] [-p] [name[=value] ...] Set variable values and attributes. Declare variables and give them attributes. If no NAMEs are given, display the attributes and values of all variables. Options: -f restrict action or display to function names and definitions -F restrict display to function names only (plus line number and source file when debugging) -g create global variables when used in a shell function; otherwise ignored -p display the attributes and value of each NAME Options which set attributes: -a to make NAMEs indexed arrays (if supported) -A to make NAMEs associative arrays (if supported) -i to make NAMEs have the `integer' attribute -l to convert the value of each NAME to lower case on assignment -n make NAME a reference to the variable named by its value -r to make NAMEs readonly -t to make NAMEs have the `trace' attribute -u to convert the value of each NAME to upper case on assignment -x to make NAMEs export Using `+' instead of `-' turns off the given attribute. Variables with the integer attribute have arithmetic evaluation (see the `let' command) performed when the variable is assigned a value. When used in a function, `declare' makes NAMEs local, as with the `local' command. The `-g' option suppresses this behavior. Exit Status: Returns success unless an invalid option is supplied or a variable assignment error occurs.
Local scope
When declare is used within a function, the variable gets a local scope, limited to inside this function. To overrule this, use the flag -g
to make them globa. E.g.:
scopetest() { unset j declare -gA j j[0,0]="00" j[0,1]="01" echo "Length - Inside function: ${#j[@]}" } unset j scopetest echo "Length - Outside function: ${#j[@]}"
Examples
Create an associative array:
declare -A j
Declare a reference for another variable:
declare -n j
Declare a variable that can only contain integers + test it:
declare -i i declare -i j i="hello, world!" j=12 echo "i: $i" echo "j: $j"
Output:
i: 0 j: 12
When putting the declare and initialization in one line, you actually get an error for the first assignment:
declare -i i="Hello, world!" declare -i j=12
The output actually puzzles me, but that's for another time and place to figure out:
bash: declare: Hello, world!: syntax error in expression (error token is "!")
You can declare multiple variables at once:
unset site site_bal site_bal_cb site_bal_non_cb site_non_bal declare -Ag site site_bal site_bal_cb site_bal_non_cb site_non_bal
See also
Sources
- https://phoenixnap.com/kb/bash-declare - Very clear!