Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print a trace of commands in bash without variable expansion

Tags:

bash

I have a script for which I'm using set -x to print a trace of the commands as they are executed.

Print a trace of simple commands, for commands, case commands, select commands, and arithmetic for commands and their arguments or associated word lists after they are expanded and before they are executed. The value of the PS4 variable is expanded and the resultant value is printed before the command and its expanded arguments.

Is there a way to get this behaviour, but not print the variable expansions? I'm capturing the log output and sending it to a centralised logger, but I do not want the value of certain sensitive variables to be output.

like image 976
obeattie Avatar asked Dec 18 '22 16:12

obeattie


1 Answers

You can use trap DEBUG with $BASH_COMMAND like so

#!/bin/bash

set -T

trap 'echo "$PS4$BASH_COMMAND"' DEBUG

i=1234

echo "$i"

(echo $i)

This will print

+ i=1234
+ echo "$i"
1234
+ echo $i
1234

BASH_COMMAND
The command currently being executed or about to be executed, unless the shell is executing a command as the result of a trap, in which case it is the command executing at the time of the trap.

-T
If set, any traps on DEBUG and RETURN are inherited by shell functions, command substitutions, and commands executed in a subshell environment. The DEBUG and RETURN traps are normally not inherited in such cases.

trap
If a sigspec is DEBUG, the command arg is executed before every simple command, for command, case command, select command, every arithmetic for command, and before the first command executes in a shell function

like image 87
123 Avatar answered Dec 21 '22 23:12

123