How to echo shell commands as they are executed How to echo shell commands as they are executed bash bash

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$


set -x will give you what you want.

Here is an example shell script to demonstrate:

#!/bin/bashset -x #echo onls $PWD

This expands all variables and prints the full commands before output of the command.

Output:

+ ls /home/user/file1.txt file2.txt


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