Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DEBUG trap storing unexpanded variable

Tags:

bash

shell

I am trying to capture the commands run in my script so they can be repeated by a logger. One of my functions executes commands stored in an array. When it does this, my DEBUG trap to store the commands in another array stores the unexpanded variable instead of the command that was run.

Here is an example:

set -o functrace
queue=("echo stuff" "echo things")
commands=()
lastcmd () { echo "Last command: ${commands[-4]}" ; }
runqueue () {
    until [[ "${#queue[@]}" == 0 ]] ; do
        ${queue[-1]}
        lastcmd
        unset "queue[-1]"
     done
}
trap 'commands+=("$BASH_COMMAND")' DEBUG
runqueue

Which results in the following output:

bash-4.4$ runqueue
things
Last command: ${queue[-1]}
stuff
Last command: ${queue[-1]}

Is there any way to record the commands post-expansion?

like image 350
MrDrMcCoy Avatar asked Sep 20 '25 17:09

MrDrMcCoy


1 Answers

Standard options to log debug information are :

  • set -v : to show command before expansion
  • set -x : to show command after expansion

in your particular case eval echo "Last command: ${commands[-4]}" ; will evaluate

eval echo "Last command: ${commands[-4]}"
# after expansion
eval echo "Last command: ${queue[-1]}"
# after eval
echo Last command: echo thing

Or easier, directly

lastcmd () { echo "Last command: ${queue[-1]}" ; }
like image 106
Nahuel Fouilleul Avatar answered Sep 22 '25 05:09

Nahuel Fouilleul