1

Is it possible to use the variables passed to printf more than once in the formatting?

For example, with this line:

printf 'Hi %s, welcome to %s. %s is a great place to work. Thanks %s.' "John" "The Icecream Factory"

How can I "reuse" the first and second variables in printf?

I'm thinking something like:

printf 'Hi %s[1], welcome to %s[2]. %s[1] is a great place to work. Thanks %s[2].' "John" "The Icecream Factory"

... but obviously that's not it.

Desired output

Hi John, welcome to The Icecream Factory. The Icecream Factory is a great place to work. Thanks John.

Actual output

Hi John, welcome to The Icecream Factory.  is a great place to work. Thanks .

Working environment is bash in Ubuntu 20.

3
  • I don't believe printf format characters support that. What's the reason you have to use %s? It's easier to define variables, which can be used multiple times in a String, e.g. n="John"; f="The Icecream Factory"; printf "Hi $n, welcome to $f. $f is a great place to work. Thanks $n." Commented Apr 25, 2021 at 4:08
  • 1
    Yes, that works fine, but I've been told it's bad practice to use variables in the printf format string: github.com/koalaman/shellcheck/wiki/SC2059 Commented Apr 25, 2021 at 5:44
  • There are pitfalls to be aware of but it's not that serious. You can also use echo instead Commented Jun 8, 2023 at 6:19

1 Answer 1

2

While I don't think it's possible using either the built-in bash implementation of printf or the freestanding GNU printf(1) program, if you can target zsh instead, its version of printf supports POSIX-style printf(3) argument indexing:

Normally, conversion specifications are applied to each argument in order but they can explicitly specify the nth argument is to be used by replacing % by %n$ and * by *n$. It is recommended that you do not mix references of this explicit style with the normal style and the handling of such mixed styles may be subject to future change.

$ printf 'Hi %1$s, welcome to %2$s. %2$s is a great place to work. Thanks %1$s.\n' "John" "The Icecream Factory"
Hi John, welcome to The Icecream Factory. The Icecream Factory is a great place to work. Thanks John.
Sign up to request clarification or add additional context in comments.

1 Comment

If this is ever added to bash, it would almost certainly use the same syntax, fwiw.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.