How can I print each command before executing?

Bash

Bash Problem Overview


What is the best way to set up a Bash script that prints each command before it executes it?

That would be great for debugging purposes.

I already tried this:

CMD="./my-command --params >stdout.txt 2>stderr.txt"
echo $CMD
`$CMD`

It's supposed to print this first:

./my-command --params >stdout.txt 2>stderr.txt

And then execute ./my-command --params, with the output redirected to the files specified.

Bash Solutions


Solution 1 - Bash

set -o xtrace

or

bash -x myscript.sh

This works with standard /bin/sh as well IIRC (it might be a POSIX thing then)

And remember, there is bashdb (bash Shell Debugger, release 4.0-0.4)


To revert to normal, exit the subshell or

set +o xtrace

Solution 2 - Bash

set -x is fine, but if you do something like:

set -x;
command;
set +x;

it would result in printing

+ command
+ set +x;

You can use a subshell to prevent that such as:

(set -x; command)

which would just print the command.

Solution 3 - Bash

The easiest way to do this is to let bash do it:

set -x

Or run it explicitly as bash -x myscript.

Solution 4 - Bash

set -x is fine.

Another way to print each executed command is to use trap with DEBUG. Put this line at the beginning of your script :

trap 'echo "# $BASH_COMMAND"' DEBUG

You can find a lot of other trap usages here.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFrankView Question on Stackoverflow
Solution 1 - BashseheView Answer on Stackoverflow
Solution 2 - BashVDarricauView Answer on Stackoverflow
Solution 3 - BashgeekosaurView Answer on Stackoverflow
Solution 4 - BashEdouard ThielView Answer on Stackoverflow