Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash "declare -p" returns incomplete info

Tags:

bash

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
like image 291
raisercostin Avatar asked Sep 18 '25 08:09

raisercostin


1 Answers

BASH_COMMAND is a dynamic variable and its value is updated only when you reference to it.

  1. Initially when Bash starts, BASH_COMMAND is only declared without being assigned with a value.
  2. 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_COMMAND before invoking test2.
    • Vars like RANDOM are similar, you can try declare -p | grep -w RANDOM.
    • Rather than declare -p | grep BASH_COMMAND you can just declare -p BASH_COMMAND.
  3. Then with value=$BASH_COMMAND it's being referenced and Bash updates it with the command which triggers the trap.
  4. And then 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.

like image 132
pynexj Avatar answered Sep 21 '25 12:09

pynexj