Skip to main content
4 of 4
Rollback to Revision 2
Jeff Schaller
  • 68.8k
  • 35
  • 122
  • 266

What is "declare" in Bash?

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 } 
user149572