sprintf
Unlike printf
which sends its output to stdout
, this function takes a variable name to store its output.
1 #!/bin/sh
2 case "$BASH_VERSION" in
3 3.1*|4.*)
4 sprintf() # $var_to_set $format [$arguments ...]
5 {
6 local __var_to_set="$1" __tmp
7 shift 1 # var_to_set
8 printf -v __tmp "$@"
9 eval $__var_to_set=\"\${__tmp%\$NL}\"
10 }
11 ;;
12 *)
13 # NB: On FreeBSD, sh(1) runs this faster than bash(1) runs the above
14 sprintf() # $var_to_set $format [$arguments ...]
15 {
16 local __var_to_set="$1"
17 shift 1 # var_to_set
18 eval $__var_to_set=\$\( printf -- \"\$@\" \)
19 }
20 esac
21 sprintf "$@"
22 eval echo \"$1=[\$$1]\"
If we detect that we are running under bash
version 3.1 or higher, the function is defined to use printf -v varname ...
because it is faster (bash
has not optimized for the case of varname=$( printf ... )
). On FreeBSD, /bin/sh
has been optimized for the case of varname=$( printf ... )
and it runs faster than bash's printf -v varname ...
syntax.
Usually varname=$( ... )
results in a sub-shell, impacting performance. On FreeBSD you can rely on the fact that calling printf
in a sub-shell does not impact performance as it does in bash
. Shells that neither provide printf -v varname ...
like bash
nor optimize for printf
in a sub-shell like FreeBSD may be slower.
Last updated
Was this helpful?