How to echo shell commands as they are executed?

2019-01-03 19:15发布

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 a a log?

标签: shell
14条回答
▲ chillily
2楼-- · 2019-01-03 19:52

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
查看更多
唯我独甜
3楼-- · 2019-01-03 19:52

Another option is to put "-x" at the top of your script instead of on the command line:

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

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

(Insufficient rep to comment on chosen answer.)

查看更多
登录 后发表回答