bash 如何在执行前打印每个命令?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5750450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I print each command before executing?
提问by Frank
What is the best way to set up a Bash script that prints each command before it executes it?
设置在执行每个命令之前打印每个命令的 Bash 脚本的最佳方法是什么?
That would be great for debugging purposes.
这对于调试目的来说非常有用。
I already tried this:
我已经试过了:
CMD="./my-command --params >stdout.txt 2>stderr.txt"
echo $CMD
`$CMD`
It's supposed to print this first:
它应该先打印:
./my-command --params >stdout.txt 2>stderr.txt
And then execute ./my-command --params
, with the output redirected to the files specified.
然后执行./my-command --params
,将输出重定向到指定的文件。
回答by sehe
set -o xtrace
or
或者
bash -x myscript.sh
This works with standard /bin/sh as well IIRC (it might be a POSIX thing then)
这适用于标准 /bin/sh 以及 IIRC(它可能是 POSIX 的事情)
And remember, there is bashdb(bash Shell Debugger, release 4.0-0.4
)
请记住,有bashdb( bash Shell Debugger, release 4.0-0.4
)
To revert to normal, exit the subshell or
要恢复正常,请退出子外壳或
set +o xtrace
回答by geekosaur
The easiest way to do this is to let bash
do it:
最简单的方法是让bash
这样做:
set -x
Or run it explicitly as bash -x myscript
.
或者将其显式运行为bash -x myscript
.
回答by VDarricau
set -x
is fine, but if you do something like:
set -x
很好,但是如果您执行以下操作:
set -x;
command;
set +x;
it would result in printing
它会导致打印
+ command
+ set +x;
You can use a subshell to prevent that such as:
您可以使用子shell来防止这种情况,例如:
(set -x; command)
which would just print the command.
这只会打印命令。