Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to 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. Is there perhaps a better way of generating such a log?

like image 613
Jack Nock Avatar asked May 18 '10 00:05

Jack Nock


People also ask

Does echo execute command?

Explanation: echo will print the command but not execute it. Just omit it to actually execute the command.

How does shell execute commands?

The shell parses the command line and finds the program to execute. It passes any options and arguments to the program as part of a new process for the command such as ps above. While the process is running ps above the shell waits for the process to complete.

How do you write an echo command?

Examples of Echo Command For instance, using \c let you shorten the output by omitting the part of the string that follows the escape character: echo -e 'Hello, World! \c This is PNAP! '


1 Answers

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.

See the bash-hackers' wiki on set attributes, and on debugging.

$ cat shl #!/bin/bash                                                                       DIR=/tmp/so ls $DIR  $ bash -x shl  + DIR=/tmp/so + ls /tmp/so $ 
like image 85
Tom Avatar answered Sep 19 '22 10:09

Tom