如何在执行 shell 命令时回显它们 [英] How to echo shell commands as they are executed
问题描述
在 shell 脚本中,如何回显所有调用的 shell 命令并扩展任何变量名称?
In a shell script, how do I echo all shell commands called and expand any variable names?
例如,给定以下行:
ls $DIRNAME
我希望脚本运行命令并显示以下内容
I would like the script to run the command and display the following
ls /full/path/to/some/dir
目的是保存所有调用的 shell 命令及其参数的日志.也许有更好的方法来生成这样的日志?
The purpose is to save a log of all shell commands called and their arguments. Is there perhaps a better way of generating such a log?
推荐答案
set -x
or set -o xtrace
展开变量并在行前打印一个小+号.
set -x
or set -o xtrace
expands variables and prints a little + sign before the line.
set -v
或 set -o verbose
不会在打印前扩展变量.
set -v
or set -o verbose
does not expand the variables before printing.
使用set +x
和set +v
关闭以上设置.
在脚本的第一行,可以输入#!/bin/sh -x
(或-v
)与效果相同稍后在脚本中设置 -x
(或 -v
).
On the first line of the script, one can put #!/bin/sh -x
(or -v
) to have the same effect as set -x
(or -v
) later in the script.
以上也适用于 /bin/sh
.
在 set
上查看 bash-hackers 维基属性,以及调试.
See the bash-hackers' wiki on set
attributes, and on debugging.
$ cat shl
#!/bin/bash
DIR=/tmp/so
ls $DIR
$ bash -x shl
+ DIR=/tmp/so
+ ls /tmp/so
$
这篇关于如何在执行 shell 命令时回显它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!