FYI, a better log_message
in bash
could be written:
exec {logfd}>> log.txt
log_message() {
local severity="$1" message
shift
for message do
printf '[%(%FT%T%z)T]-[%s] : %s\n' -1 "$severity" "$message" >&"$logfd"
done
}
Which avoids running one date
command and reopening the log file each time, and lets you pass more than one message (each message displayed on a separate line).
Then use \
for line continuation as already mentioned by @AdminBee. Note that in sh/bash, as opposed to most other languages, it's around parameter expansions or characters that are special to the shell that you need to but the quotes. With "...."${var}"..."
you ended up leaving the ${var}
unquoted which meant it undergoes split+glob!
log_message WARNIN\
G "I am ${varName}\
and I want to lim\
it this line to 20\
columns"
Is an option. Beware line continuations like that (with \
followed by newline), works inside or outside double quotes, or in here documents, but not inside single quotes nor here-documents with a quoted delimiter.
With that log_message
, you could also do:
log_message WARNING \
"I am ${varName}" \
'and I want to limit' \
'the length of the lines' \
'in the log file.'
To get in log.txt
:
[2022-06-24T13:28:46+0100]-[WARNING] : I am John Doe
[2022-06-24T13:28:46+0100]-[WARNING] : and I want to limit
[2022-06-24T13:28:46+0100]-[WARNING] : the length of the lines
[2022-06-24T13:28:46+0100]-[WARNING] : in the log file.
https://shellcheck.net
, a syntax checker, or installshellcheck
locally. Make usingshellcheck
part of your development process. – waltinator Jun 24 '22 at 16:50