The best answers to the question “How can I print each command before executing? [duplicate]” in the category Dev.
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.
The easiest way to do this is to let
bash do it:
Or run it explicitly as
bash -x myscript.
set -o xtrace
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
set -x is fine.
Another way to print each executed command is to use
Put this line at the beginning of your script :
trap 'echo "# $BASH_COMMAND"' DEBUG
You can find a lot of other
trap usages here.
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.