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
BASH_COMMAND
is a dynamic variable and its value is updated only when you reference to it.
BASH_COMMAND
is only declared without being assigned with a value.declare -p | grep BASH_COMMAND
(no matter how many times) the var is still not referenced yet so it still has no value.
v=$BASH_COMMAND
before invoking test2
.RANDOM
are similar, you can try declare -p | grep -w RANDOM
.declare -p | grep BASH_COMMAND
you can just declare -p BASH_COMMAND
.value=$BASH_COMMAND
it's being referenced and Bash updates it with the command which triggers the trap.declare -p
can 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With