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

例如,给定以下一行:

ls $DIRNAME

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

ls /full/path/to/some/dir

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


当前回答

$ cat exampleScript.sh
#!/bin/bash
name="karthik";
echo $name;

bash -x exampleScript.sh

输出结果如下:

其他回答

对于zsh,使用echo

setopt VERBOSE

为了调试,

setopt XTRACE

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

bash -x foo.sh

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

#!/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

您还可以通过将脚本中的选定行包装在set -x和set +x中来切换此选项,例如,

#!/bin/bash
...
if [[ ! -e $OUT_FILE ]];
then
   echo "grabbing $URL"
   set -x
   curl --fail --noproxy $SERV -s -S $URL -o $OUT_FILE
   set +x
fi

Set -x会得到你想要的。

下面是一个示例shell脚本来演示:

#!/bin/bash
set -x #echo on

ls $PWD

这将展开所有变量,并在输出命令之前打印完整的命令。

输出:

+ ls /home/user/
file1.txt file2.txt