In a shell script: echo shell commands as they are executed

In a shell script how do I echo all shell commands called and expand any variable names? For example, given the following line:

ls $DIRNAME

I would like the script to run the command and display the following

ls /full/path/to/some/dir

The purpose is to save a log of all shell commands called and their arguments. Perhaps there is a better way of generating such aa log?


set -x or set -o xtrace expands variables and prints a little + sign before the line.

set -v or set -o verbose does not expand the variables before printing.

Use set +x and set +v to turn off the above settings.

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.

The above also works with /bin/sh .

http://www.faqs.org/docs/abs/HTML/options.html

$ cat shl
#!/bin/bash                                                                     

DIR=/tmp/so
ls $DIR

$ bash -x shl 
+ DIR=/tmp/so
+ ls /tmp/so
$

set -x will give you what you want.

Here is an example shell script to demonstrate:

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

ls $PWD

This expands all variables and prints the full commands before output of the command.

output:

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

你也可以在你的脚本中通过将它们包装在set -xset +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
链接地址: http://www.djcxy.com/p/2892.html

上一篇: 检查Bash shell脚本中是否存在输入参数

下一篇: 在shell脚本中:echo shell命令执行时