4

Is there a way to run scripts in bash that makes it so that it prints each line of the script before executing it? This would be really useful to me for debugging...

$./myscript.sh
echo "Hello"
Hello

I would be able to see exactly how far my script has gotten, and what it is doing.

slm
  • 369,824
Questionmark
  • 3,945

1 Answers1

8

You can enable/disable this feature through the use of the set command, and the option -x/+x.

-x - After expanding each simple command, for command, case command, select command, or arithmetic for command, display the expanded value of PS4, followed by the command and its expanded arguments or associated word list.

-x enables it, +x disables it.

Example

sample script

$ cat ~/myscript.sh 
#!/bin/bash

set -x
echo "Hello"

sample output

$ ~/myscript.sh 
+ echo Hello
Hello
slm
  • 369,824
  • 2
    To expand on this, you can get really creative and set PS4='${LINENO}+, which will also tell you which line of the script expands to what is being run. For the above, example, the output would be 4+ echo Hello followed by Hello. – DopeGhoti Oct 27 '14 at 19:52