Showing the running command in a bash script with "set -x"

29 May, 2009 - 09:03

Bash scripts are handy for putting a bunch of longer running jobs in one batch. In some occasions it can be useful to know which command is running at the moment, especially when the commands do not generate output themselves or this output is redirected to files.

Bash has a simple setting to achieve this:

set -x

which, according to help set, enables the following feature:

-x Print commands and their arguments as they are executed.

Disabling it just takes a mere

set +x

You can play with it from the bash command line itself, or put it in a bash script of course.

A simple illustration with this bash script put_out_the_trash.sh that contains silent commands:

#!/bin/bash
 
set -x
 
touch cookiewrap
mv cookiewrap dustbin
mv dustbin trashcan_kitchen
mv trashcan_kitchen outside

Running the script from the command line gives you:

$ ./put_out_the_trash.sh
+ touch cookiewrap
+ mv cookiewrap dustbin
+ mv dustbin trashcan_kitchen
+ mv trashcan_kitchen outside
$

So you see what's happening.