# 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.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://freebsdfrau.gitbook.io/serious-shell-programming/string-functions/sprintf.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
