Bash – Understanding the ‘declare’ Command

bashcontrol flowdeclarefunctionshell-builtin

After reading ilkkachu's answer to this question I learned on the existence of the declare (with argument -n) shell built in.

help declare brings:

Set variable values and attributes.

Declare variables and give them attributes. If no NAMEs are given,
display the attributes and values of all variables.

-n … make NAME a reference to the variable named by its value

I ask for a general explanation with an example regarding declare because I don't understand the man. I know what is a variable and expanding it but I still miss the man on declare (variable attribute?).

Maybe you'd like to explain this based on the code by ilkkachu in the answer:

#!/bin/bash
function read_and_verify  {
    read -p "Please enter value for '$1': " tmp1
    read -p "Please repeat the value to verify: " tmp2
    if [ "$tmp1" != "$tmp2" ]; then
        echo "Values unmatched. Please try again."; return 2
    else
        declare -n ref="$1"
        ref=$tmp1
    fi
}

Best Answer

In most cases it is enough with an implicit declaration in bash

asdf="some text"

But, sometimes you want a variable's value to only be integer (so in case it would later change, even automatically, it could only be changed to an integer, defaults to zero in some cases), and can use:

declare -i num

or

declare -i num=15

Sometimes you want arrays, and then you need declare

declare -a asdf   # indexed type

or

declare -A asdf   # associative type

You can find good tutorials about arrays in bash when you browse the internet with the search string 'bash array tutorial' (without quotes), for example

linuxconfig.org/how-to-use-arrays-in-bash-script


I think these are the most common cases when you declare variables.


Please notice also, that

  • in a function, declare makes the variable local (in the function)
  • without any name, it lists all variables (in the active shell)

    declare
    

Finally, you get a brief summary of the features of the shell built-in command declare in bash with the command

help declare
Related Question