Reputation: 10902
Would you quote this variable assignment which builds a log message from some pre-calculated components?
formatted_message=$(printf '%s [PID %s] %s (%s) %s:%s | %s\n' \
"${TIMESTAMP}" \
"${PROCESS}" \
"${SEVERITY}" \
"${SOURCE}" \
"${FUNCTION}" \
"${LINE}" \
"${MESSAGE}")
Is this good Bash programming style actually?
I am loving trying to learn some Bash but there is something which I find "inefficient":
Let's take an example that threw me into this state of confusion about "best coding practices":
[[ $x == "$x" ]]
I can omit the quotes on the left without any real change in behaviour.. adding them to the right side of the evaluation has an important effect. All of a sudden, I wonder about process substitution and all other contexts of "evaluation/substitution" and wish there was one simple way to do it, with few exceptions.
If there was a guiding article/blog post for this I would really study it in detail, coming to an understanding (hopefully) of what a real Bash programmer wants to convey when he/she puts quotes in a particular position of omits them.
Note: my learning happens in a tollbooth at night. I have no fellow programmers apart from you guys here to compare my views with and some open-source code is "just out there", without accompanying comments justifying choices as subtle as "coding style".
Another point: I find it easier to always type:
printf "${my_string_var}"
but of course this is fine as well:
printf "$my_string_var"
(I just happen to "see" the variable expansion better with the {}
)
but this probably won't be equivalent for word-split variable contents (?!)
printf $my_string_var # with $my_string_var := 'foo bar'
If you just want to answer one simple, straight-forward question and stay clear of a "debate":
Note: one of my problems was that the final \n
disappears, even if I try to put double quotes here and there.. but now I understand that $()
strips it..
Upvotes: 2
Views: 265
Reputation: 532268
I would not quote the right-hand side, as the usual reason (protect against inadvertent word-splitting) does not apply to the RHS of a variable assignment.
If you are using bash
4 or later, you can dispense with the assignment altogether. Along with that, I find the braces unnecessary and distracting if you don't need them for applying a parameter expansion operator or isolating the parameter name from an adjacent character. Quoting remains important, of course.
printf -v formatted_message '%s [PID %s] %s (%s) %s:%s | %s\n' \
"$TIMESTAMP" \
"$PROCESS" \
"$SEVERITY" \
"$SOURCE" \
"$FUNCTION" \
"$LINE" \
"$MESSAGE"
Upvotes: 1