What is "declare" in Bash?
66
votes
5
answers
77086
views
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
}
Asked by user149572
Apr 3, 2019, 06:49 AM
Last activity: Jun 11, 2025, 10:39 AM
Last activity: Jun 11, 2025, 10:39 AM