在一个shell脚本,我如何回显所有shell命令调用和展开任何变量名?
例如,给定以下一行:
ls $DIRNAME
我希望脚本运行该命令并显示以下内容
ls /full/path/to/some/dir
目的是保存所有调用的shell命令及其参数的日志。是否有更好的方法来生成这样的日志?
在一个shell脚本,我如何回显所有shell命令调用和展开任何变量名?
例如,给定以下一行:
ls $DIRNAME
我希望脚本运行该命令并显示以下内容
ls /full/path/to/some/dir
目的是保存所有调用的shell命令及其参数的日志。是否有更好的方法来生成这样的日志?
当前回答
可以使用-x选项在调试模式下执行Bash脚本。
这将回显所有命令。
bash -x example_script.sh
# Console output
+ cd /home/user
+ mv text.txt mytext.txt
您也可以在脚本中保存-x选项。只需在shebang中指定-x选项。
######## example_script.sh ###################
#!/bin/bash -x
cd /home/user
mv text.txt mytext.txt
##############################################
./example_script.sh
# Console output
+ cd /home/user
+ mv text.txt mytext.txt
其他回答
可以使用-x选项在调试模式下执行Bash脚本。
这将回显所有命令。
bash -x example_script.sh
# Console output
+ cd /home/user
+ mv text.txt mytext.txt
您也可以在脚本中保存-x选项。只需在shebang中指定-x选项。
######## example_script.sh ###################
#!/bin/bash -x
cd /home/user
mv text.txt mytext.txt
##############################################
./example_script.sh
# Console output
+ cd /home/user
+ mv text.txt mytext.txt
我使用一个函数来回显并运行命令:
#!/bin/bash
# Function to display commands
exe() { echo "\$ $@" ; "$@" ; }
exe echo hello world
的输出
$ echo hello world
hello world
对于更复杂的命令管道等,你可以使用eval:
#!/bin/bash
# Function to display commands
exe() { echo "\$ ${@/eval/}" ; "$@" ; }
exe eval "echo 'Hello, World!' | cut -d ' ' -f1"
的输出
$ echo 'Hello, World!' | cut -d ' ' -f1
Hello
对于csh和tcsh,可以设置verbose或设置echo(甚至可以同时设置两者,但大多数时候可能会导致一些重复)。
verbose选项几乎打印您键入的shell表达式。
echo选项更能说明通过生成将执行什么。
http://www.tcsh.org/tcsh.html/Special_shell_variables.html#verbose
http://www.tcsh.org/tcsh.html/Special_shell_variables.html#echo
特殊的壳变量
详细的 如果设置,则导致在历史替换(如果有)之后打印每个命令的单词。由-v命令行选项设置。
回声 如果设置了,每个命令及其参数都会在执行之前被回显。对于非内置命令,所有展开都发生在回显之前。内置命令在命令和文件名替换之前被回显,因为这些替换是选择性地完成的。由-x命令行选项设置。
对于zsh,使用echo
setopt VERBOSE
为了调试,
setopt XTRACE
另一种选择是在你的脚本顶部放置"-x",而不是在命令行上:
$ cat ./server
#!/bin/bash -x
ssh user@server
$ ./server
+ ssh user@server
user@server's password: ^C
$