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,379
Putnik
  • 945

4 Answers4

45

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
  • 111,893
21

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
  • 111,893
7

set -x is an equivalent of "echo on"

set +x is an equivalent of "echo off"

0

No one mentioned set -v, which displays the line as they are read:

#!/bin/bash

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

Producing:

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