Skip to content
Fix Code Error

How to echo shell commands as they are executed

March 13, 2021 by Code Error
Posted By: Anonymous

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?

Solution

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
$
Answered By: Anonymous

Related Articles

  • What does %~dp0 mean, and how does it work?
  • What are the undocumented features and limitations of the…
  • Why doesn't Python have a sign function?
  • AppCompat v7 r21 returning error in values.xml?
  • Npm run serve Error
  • What is the best way to do a substring in a batch file?
  • Error : Ineffective mark-compacts near heap limit Allocation…
  • What is your most productive shortcut with Vim?
  • "npm run build" error when building on VSTS/Azure DevOps
  • How can I get the source directory of a Bash script from…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

UnicodeDecodeError, invalid continuation byte

Next Post:

Maximum request length exceeded.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Get code errors & solutions at akashmittal.com
© 2022 Fix Code Error