'how to print out all commands in bash script [duplicate]
I know "set -x" will print out commands in current script. but if the script a.sh runs b.sh then b.sh won't print out commands. is there a way set -x globally so all commands print out?
x@ASUS:~$ cat a.sh
#!/bin/bash
set -x
echo "a.sh"
./b.sh
x@ASUS:~$ cat b.sh
#!/bin/bash
echo "b.sh"
x@ASUS:~$ ./a.sh
Solution 1:[1]
Yes, you need to source the second script instead of executing it.
Executing it will spawn a new shell, which is not affect by set -x
.
Sourcing it will instead execute the script in the current shell, where you've run set -x
.
[1:24 anon] ~$ cat ./a.sh
#!/bin/bash
set -x
echo "a.sh"
source ./b.sh
[1:26 anon] ~$ cat ./b.sh
#!/bin/bash
echo "b.sh"
[1:26 anon] ~$ ./a.sh
+ echo a.sh
a.sh
+ source ./b.sh
++ echo b.sh
b.sh
Solution 2:[2]
As long as b.sh
does not call set +x
, then you can do:
export SHELLOPTS
set -x
This should survive intermediate non-bash subprocesses that don't sanitise their environment, but only works with bash scripts (eg. scripts with #!/bin/sh
bang-path won't display traces).
bash$ cat <<'EOD' >a2.sh
#!/bin/bash
export SHELLOPTS
set -x
echo "a2.sh"
awk 'BEGIN{system("echo a1");system("bash -c \"echo a2\"");system("./b.sh") }'
./b.sh
EOD
bash$ chmod +x a2.sh
bash$ ./a2.sh
+ echo a2.sh
a2.sh
+ awk 'BEGIN{system("echo a1");system("bash -c \"echo a2\"");system("./b.sh") }'
a1
+ echo a2
a2
+ echo b.sh
b.sh
+ ./b.sh
+ echo b.sh
b.sh
bash$
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Layne Bernardo |
Solution 2 |