Issue
Assuming I have a bash script test.sh
:
#!/bin/bash
# Comment 1
echo "Hello world"
# Comment 2
echo "Hi there"
I know after making the bash script executable and running it, only the echo
commands would show as output.
I'm wondering if there's a way to print the comments on execution. That is, I want the output to look like:
Comment 1
Hello world
Comment 2
Hi there
Edit:
Even after 2 years, I keep getting linked back to this question.
After more experience, I would like to admit that I don't even know why I expected this to have an answer. Comments are a communication tool meant to provide developers more understanding about a given piece of code.
Since I can't delete it because StackOverflow prevents me from doing so, here's the response.
No. No trivial, inbuilt solution exists at this time to the question "Can you print the comments in a bash script, whiles running the same script?"
You can however use the set builtin, specifically set -v
, to print out bash commands in a script, as they're being executed.
Solution
A common arrangement is to have various logging levels set up, and then emit different amounts of logging depending on the logging level.
debug () { ${debug-:} "$0: $@" >&2; }
info () { ${info-:} "$0: $@" >&2; }
warn () { ${warn-:} "$0: $@" >&2; }
error () { ${error-:} "$0: $@" >&2; }
case $1 in
--debug) debug=echo; info=echo; warn=echo; error=1;;
--info) info=echo; warn=echo; error=1;;
--warn) warn=echo; error=echo;;
--error) error=echo;;
-*) echo "$0: unknown option '$1' -- aborting" >&2
exit 127;;
esac
shift
debug here we go
info starting
echo "Hello world"
warn the end is nigh
echo "Hi there"
error we die here
exit 42
This is just a dead simple demo; you would probably want for it to be somewhat more secure and versatile, and have sensible default like running with --warn
(which implies --error
) if no level is explicitly specified.
The "comments" are no longer comments, and the output goes to standard error in this implementation; but as you can see, this also lets you put in "comments" which are actually useful when you are debugging, not just while reading the code.
You can make the commands (debug
, warn
etc) look more like comments by renaming them, perhaps to _dbg_
, _warn_
etc.
Answered By - tripleee Answer Checked By - Marie Seifert (WPSolving Admin)