bash printf with new line bash printf with new line bash bash

bash printf with new line


printf's %b format specifier was meant specifically to replace echo -e (actually, the XSI extension to echo which calls for special interpretation of the arguments by default. -e was never specified and is disallowed by POSIX.), and is identical in virtually every way including a few differences from $'...' and the format string argument to printf.

 $ ( var='Age:\n20\ncolor:\nred'; printf '%b\n' "$var" )Age:20color:red

You should generally avoid expanding variables into the format string unless your program controls the exact value and it is intended specifically to be a format string. Your last example in particular has the potential to be quite dangerous in Bash due to printf's -v option.

# Bad!var='-v_[$(echo "oops, arbitrary code execution" >&2)0]'printf "$var" foo

It is usually good practice to avoid %b unless you have a special portability requirement. Storing the escape codes in a variable instead of the literal data violates principles of separation of code and data. There are contexts in which this is ok, but it is usually better to assign the the value using $'...' quoting, which is specified for the next version of POSIX, and has long been available in Bash and most ksh flavours.

x=$'foo\nbar'; printf '%s\n' "$x"    # Goodx=(foo bar); printf '%s\n' "${x[@]}" # Also good (depending on the goal)x='foo\nbar'; printf '%b\n' "$x"     # Ok, especially for compatibilityx='foo\nbar'; printf -- "$x"         # Avoid if possible, without specific reason