I am just getting a little more comfortable with Bash.
I wanted a super simple log function to write to a file and output to the console for messages and errors. I also wanted the terminal and the file to interpret newline characters rather than printing them out. Here is what I came up with (it works fine):
#!/bin/bash
log () {
if [[ "$3" == '-e' || "$3" == '--error' ]]; then
>&2 echo -e "ERROR: $1" && printf "ERROR: $1\n" >> "$2"
else
echo -e "$1" && printf "$1\n" >> "$2"
fi
}
# Example implementation
log_file=snip/init.log
msg="\nthis is an error message with leading newline character"
log "$msg" $log_file -e
msg="this is success message with no newline characters"
log "$msg" $log_file
I don't need any more functionality however I have some questions:
- Is an efficient and readable piece of code that won't break when passed strings with special characters?
- Syntactically, could I have done this 'better' such as using pipes instead of
&&.teeinstead ofprintfetc.? - How can I refactor this code to allow for the optional
-eflag to be passed in first?
log [OPTIONS] LOG_FILE MESSAGE...". So when called it would look like thislog "$log_file" "Part1" "Part 2" "and so on"` orlog --error "$log_file" "Part1" "Part 2" "and so on". \$\endgroup\$-efirst, usingifandshift. But it might be better to have two different functions, and that's what I propose in my answer. \$\endgroup\$