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?
Standard options to log debug information are :
set -v
: to show command before expansionset -x
: to show command after expansionin 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]}" ; }
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