在一个shell脚本,我如何回显所有shell命令调用和展开任何变量名?

例如,给定以下一行:

ls $DIRNAME

我希望脚本运行该命令并显示以下内容

ls /full/path/to/some/dir

目的是保存所有调用的shell命令及其参数的日志。是否有更好的方法来生成这样的日志?


当前回答

另一种选择是在你的脚本顶部放置"-x",而不是在命令行上:

$ cat ./server
#!/bin/bash -x
ssh user@server

$ ./server
+ ssh user@server
user@server's password: ^C
$

其他回答

对于zsh,使用echo

setopt VERBOSE

为了调试,

setopt XTRACE

另一种选择是在你的脚本顶部放置"-x",而不是在命令行上:

$ cat ./server
#!/bin/bash -x
ssh user@server

$ ./server
+ ssh user@server
user@server's password: ^C
$

我使用一个函数来回显并运行命令:

#!/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
$ cat exampleScript.sh
#!/bin/bash
name="karthik";
echo $name;

bash -x exampleScript.sh

输出结果如下:

在命令行上,在bash脚本名称之前键入“bash -x”。例如,要执行foo.sh,输入:

bash -x foo.sh