How can I print each command before executing? [duplicate]

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.


Solution 1:

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:

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

set -x

Or run it explicitly as bash -x myscript.