Wednesday, January 16, 2013

How to make bash scripts print out every command before it executes?

How to make bash scripts print out every command before it executes?
up vote 14 down vote favorite
4


For example, I have a simple bash file

#!/bin/bash
cd ~/hello
ls

How can I make it display every command before executing it? Just the opposite effect of "@echo off" in windows batch scripting.
bash scripting
share|improve this question

asked May 31 '09 at 13:39
Epeius
7326

feedback
7 Answers
active oldest votes
up vote 28 down vote accepted


bash -x script

or

set -x

in the script
share|improve this answer

answered May 31 '09 at 13:44
Steven Parkes
39534


I have always used this to great effect. The output looks a little dirtier than you might first expect. – Scott Pack May 31 '09 at 13:51
feedback
up vote 10 down vote


These also work:

set -v

or

#!/bin/bash -v

But -v doesn't print the PS4 string before each script line and it doesn't trace the steps of a "for" statement (for example) individually. It does echo comments while -x doesn't.

Here's an example of the output using -v:

#!/bin/bash -v
# this is a comment
for i in {1..4}
do
echo -n $i
done
1234echo

echo hello
hello

Here's the result of the same script with -x:

+ for i in '{1..4}'
+ echo -n 1
1+ for i in '{1..4}'
+ echo -n 2
2+ for i in '{1..4}'
+ echo -n 3
3+ for i in '{1..4}'
+ echo -n 4
4+ echo

+ echo hello
hello

Note that I included "echo -n" to add emphasis to the differences between -v and -x. Also, -v is the same as "-o verbose", but the latter seems not to work as part of a shebang.

No comments:

Post a Comment