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?
For zsh echo
and for debugging
You can also toggle this for select lines in your script by wrapping them in
set -x
andset +x
e.g.I use a function to echo then run the command
Which outputs
Edit:
For more complicated commands pipes etc you can use eval:
Which outputs
According to TLDP's Bash Guide for Beginners: Chapter 2. Writing and debugging scripts
Someone above posted:
and this looks promising, but I can't for the life of me figure out what it does. I've googled and searched in the man bash page for "\$" and "$@", and find absolutely nothing.
I understand a function is being created, named "exec()". I understand the curly-brackets mark the beginning and end of the function. I think I understand that the semi-colon marks a "hard return" between a multi-line command, so that '{ echo "\$ $@" ; "$@" ; }' becomes, in essence:
Can any one give me a brief explanation, or where to find this info, since obviously my google-fu is failing me?
(Without meaning to start a new question on an old thread, my goal is to reroute the output to a file. The "set -x ; [commands] ; set +x" method would work adequately well for me, but I can't figure out how to echo the results to a file instead of the screen, so I was trying to understand this other method in hopes I could use me very poor understanding of redirection/pipes/tee/etc to do the same thing.)
Thanks!
LATER EDIT:
With some tinkering, I believe I figured it out. Here's my equivalent code for what I'm needing:
The results in the logfile.txt look something like:
Just what I needed. Thanks!
You can execute a bash script in debug mode with the -x option.
This will echo all the commands.
You can also save the -x option in the script. Just specify the -x option in the shebang.