41

How can I get to stdout all commands that run in bash script?

That is output must contain commands output AND commands themselves.

I found

#!/bin/bash -x

but this is not exactly the same because instead of

 mysql -v dbname < dump.sql | grep "CREATE TABLE"

it shows

+ mysql -v dbname
+ grep 'CREATE TABLE'
N.N.
  • 1,381
  • 2
  • 17
  • 34
Putnik
  • 912
  • 1
  • 6
  • 16

3 Answers3

41

Use bash -v.

This is the script:

#!/bin/bash -v

echo "Hello, World" | sed 's|Hello|Goodbye|'

echo "Done."

This is the output:

#!/bin/bash -v

echo "Hello, World" | sed 's|Hello|Goodbye|'
Goodbye, World

echo "Done."
Done.

Unfortunately, there is no special marker like PS4 for printing expanded commands. You could combine both though to quickly identify commands:

#!/bin/bash -vx

echo "Hello, World" | sed 's|Hello|Goodbye|'
+ echo 'Hello, World'
+ sed 's|Hello|Goodbye|'
Goodbye, World

echo "Done."
+ echo Done.
Done.
Daniel Beck
  • 109,300
  • 14
  • 287
  • 334
19

set -x is other way of doing it.

$ cat a.sh
#!/bin/bash

set -x
echo "Hello, World" | sed 's|Hello|Goodbye|'
echo "Done."

Output will be:

sh a.sh
+ echo 'Hello, World'
+ sed 's|Hello|Goodbye|'
Goodbye, World
+ echo Done.
Done.
Daniel Beck
  • 109,300
  • 14
  • 287
  • 334
Ashok Vairavan
  • 311
  • 1
  • 3
  • 2
    Which is kind of what the OP dismissed as useless right in his question... – Daniel Beck Feb 07 '12 at 18:12
  • @Ashok Could you please explain? I can't see the difference: [here](http://pastebin.com/AParHsuA) p.s.: GNU bash, version 4.1.5(1)-release (i486-pc-linux-gnu) Ubuntu 10.04.3 – Putnik Feb 08 '12 at 13:49
  • 1
    @Putnik It's the same basic thing, but you can `set -x` anywhere in the script, and even deactivate it again. So if you only want it on the `echo "Done"` line, put `set -x` just before that one. – Daniel Beck Feb 08 '12 at 15:09
  • landed here through a search engine, found your answer helpful. Thx – studioj Nov 01 '21 at 19:22
6

set -x is an equivalent of "echo on"

set +x is an equivalent of "echo off"