What is the difference between `echo` and `printf`, and why do production scripts prefer `printf`?
IntermediateConceptVariables, quoting and expansions
Answer
echo behaviour varies: some shells interpret \n by default, -e/-n are not portable, and a value like -n or -e is swallowed as an option. printf is consistent everywhere and supports formatting.
printf '%s\n' "$user_input" # always prints the value literally
printf '%-20s %5d%%\n' "/var" 93 # aligned columns
printf -v stamp '%(%Y-%m-%dT%H:%M:%S)T' -1 # timestamp, no fork (Bash 4.2+)
Rule: echo for fixed strings, printf '%s\n' for anything containing variables.
More on Variables, quoting and expansions
What are the rules for assigning variables in Bash?BeginnerWhat is the difference between single quotes, double quotes and `$'...'`?BeginnerWhy should you almost always quote variable expansions? Show what goes wrong.BeginnerExplain the difference between `"$@"`, `"$*"`, `$@` and `$*`.IntermediateWhat do `${var:-default}`, `${var:=default}`, `${var:+alt}` and `${var:?msg}` do?IntermediateHow do you strip prefixes and suffixes with parameter expansion?Intermediate