How to echo shell commands as they are executed
set -x
or set -o xtrace
expands variables and prints a little + sign before the line.
set -v
or set -o verbose
does not expand the variables before printing.
Use set +x
and set +v
to turn off the above settings.
On the first line of the script, one can put #!/bin/sh -x
(or -v
) to have the same effect as set -x
(or -v
) later in the script.
The above also works with /bin/sh
.
See the bash-hackers' wiki on set
attributes, and on debugging.
$ cat shl#!/bin/bash DIR=/tmp/sols $DIR$ bash -x shl + DIR=/tmp/so+ ls /tmp/so$
I use a function to echo and run the command:
#!/bin/bash# Function to display commandsexe() { echo "\$ $@" ; "$@" ; }exe echo hello world
Which outputs
$ echo hello worldhello world
For more complicated commands pipes, etc., you can use eval:
#!/bin/bash# Function to display commandsexe() { echo "\$ ${@/eval/}" ; "$@" ; }exe eval "echo 'Hello, World!' | cut -d ' ' -f1"
Which outputs
$ echo 'Hello, World!' | cut -d ' ' -f1Hello