Having the following script test1.sh I'm wondering what is the reason of not getting the full list of declared variables with declare -p. For BASH_COMMAND surprisingly I'm not seeing the value but only declare -- BASH_COMMAND. After the variable is used then declare -p returns it properly.
What is the reason behind? What am I missing? I couldn't find the meaning of the declare -- also. What can I do to see all the variables for debug purpose?
#!/bin/bash
set -o errexit -o pipefail -o noclobber -o nounset -o posix -o errtrace -o functrace -o hashall
# -o xtrace
function trapExit() {
#here we get the INCORECT declare with BASH_COMMAND having no value
declare -p | grep BASH_COMMAND
declare -p | grep BASH_COMMAND
value=$BASH_COMMAND
#here we get the CORRECT declare with BASH_COMMAND having the value
declare -p | grep BASH_COMMAND
echo "valueOfCommand=$value"
}
function test2() {
${MISSING_PARAM?"Parameter is missing in function test2"}
}
trap trapExit exit
test2
: <<END_COMMENT
$ ./test1.sh
./test1.sh: line 15: MISSING_PARAM: Parameter is missing in function test2
declare -- BASH_COMMAND
declare -- BASH_COMMAND="\${MISSING_PARAM?\"Parameter is missing in function test2\"}"
valueOfCommand=${MISSING_PARAM?"Parameter is missing in function test2"}
END_COMMENT
CodePudding user response:
BASH_COMMAND is a dynamic variable and its value is updated only when you reference to it.
- Initially when Bash starts,
BASH_COMMANDis only declared without being assigned with a value. - When you
declare -p | grep BASH_COMMAND(no matter how many times) the var is still not referenced yet so it still has no value.- This can be verified by adding
v=$BASH_COMMANDbefore invokingtest2. - Vars like
RANDOMare similar, you can trydeclare -p | grep -w RANDOM. - Rather than
declare -p | grep BASH_COMMANDyou can justdeclare -p BASH_COMMAND.
- This can be verified by adding
- Then with
value=$BASH_COMMANDit's being referenced and Bash updates it with the command which triggers the trap. - And then
declare -pcan also show its value.
-- as in declare -- has no special meaning. It just "signals the end of options and disables further option processing" though it's not really necessary for this case.
