Printf – store formatted string output in a variable

bashprintfvariablevariable substitution

Instead of the following

printf '%s\t%s\t%s\t%s\n' 'index' 'podcast' 'website' 'YouTube'

I want to store the printf output in a Results variable, how can I do this?

Best Answer

Bash (since 3.1), zsh (since 5.3) and ksh93 (since v- and u+m 2021-11-28) have an "assignment to variable option" for printf:

$ Row='%s\t%s\t%s\t%s\n'
$ printf -v Result -- "${Row}" 'index' 'podcast' 'website' 'YouTube'
$ echo "${Result}"
index   podcast website YouTube

$ 

Notice I get two newlines -- one from the printf format, the other from the echo.

You could also control the column widths using something like $-10s for each field, instead of tabbing.

The advantage of this over the $( ... ) or `back-quote` syntax, in addition to preserving trailing newlines is that it does not need to run a subshell for the assignment which in shells other than ksh93¹ is relatively costly.


¹ It's less costly in ksh93 where it doesn't involve a fork but can be made even less so there with the ${ printf...; } form of substitution. That one will be supported in the next version of bash after 5.2.x as well as the next version of zsh after 5.9.x as well as the ${|...} variant from mksh

Related Question