2 ms·
I'm surprised that no one mentioned a pair of tiny functions to log each command before it is run. Nicer versions also print a timestamp. Of course, this setu
by throwaway2037 4y ago
I'm surprised that no one mentioned a pair of tiny functions to log each command before it is run. Nicer versions also print a timestamp. Of course, this setup assumes: set -e
echo_command()
{
echo
echo '$' "$@"
}
echo_and_run_command()
{
echo_cmd "$@"
"$@"
}
Then something like:
main()
{
# For simple commands that do not use | < > etc.
echo_and_run_command cp --verbose ...
# More complex commands
echo_command grep ... '|' find ...
grep ... | find ...
}
main "$@"
- jpitz 4y agoIt does not address timestamps, but set -x does this seamlessly without cluttering up your script. You can even run your script with sh -x script If you didn't always want the logging output.
- memco 4y agoIn addition to set -x I have taken to wrapping my main entry point in some scripts where record keeping is helpful in a sub shell and pipe all output to a function that tees it's output to a log file after cleaning up escape sequences so I can generate a log file without having to annotate every line with some kind of wrapper: #!/usr/bin/env bash ( foo bar ) 2>&1 | print_and_log "$logfile"
- ndsipa_pomu 4y agoI feel like I'm spamming these comments with this, but check out https://bash3boilerplate.sh/ https://bash3boilerplate.sh/ for a much better logging system along with a neat way of parsing options. You define the usage and help section like so to define your options: ### Usage and help - change this for each script ############################################################################## # shellcheck disable=SC2015 [[ "${__usage+x}" ]] || read -r -d '' __usage <<-'EOF' || true # exits non-zero when EOF encountered -t --timestamps Enable timestamps in output -v --verbose Enable verbose mode, print script as it is executed -d --debug Enables debug mode -h --help This page -n --no-color Disable color output EOF Then you get to refer to ${arg_t} for the --timestamps option etc.