Serious Shell Programming
  • Introduction
  • Acknowledgements
  • Basics
    • Strings
      • Single-Quotes
      • Double-Quotes
      • Unquoted Strings
      • Compound Strings
    • Here Documents
      • Here Doc
      • Indented Here Doc
      • Literal Here Doc
      • In-Memory Here Doc
    • Conditionals
      • Built-in test
      • Parameter Conditionals
      • Parameter test
    • Regex
      • grep
      • awk
      • pcre
    • Control Flow
      • Binary Operators
      • if-elif-else
      • case Statement
      • for Loop
      • while Loop
      • Functions
  • shellcheck
    • Introduction
    • Bad Advice
  • Style
    • awk
    • case
    • Redirection
    • Comments
    • trap
  • String Functions
    • substr
    • sprintf
    • replace
    • replaceall
    • replacestart
    • replaceend
    • fnmatch
  • awk
    • Pre-declaring Arrays
    • Sorting Arrays
  • Know Your limits
    • Arguments
    • Environment Variables
    • Solutions
Powered by GitBook
On this page

Was this helpful?

  1. String Functions

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.

PrevioussubstrNextreplace

Last updated 5 years ago

Was this helpful?