2

You know that the printf function written in C allows to do:

printf('%2$s %2$s %1%s %1%s', 'World', 'Hello');

Hello Hello World World

But in GNU Bash:

printf '%2$s %2$s %1%s %1%s' 'World' 'Hello'

bash: printf: $': invalid format character

Also for /usr/bin/printf:

/usr/bin/printf '%2$s %2$s %1%s %1%s' 'World' 'Hello'

/usr/bin/printf: %2$: invalid conversion specification

How to obtain the C behavior in Bash? Thanks.

Edited:

I was curious about this behaviour, I don't want a workaround.

Edited:

E.g. think about GNU Bash source code internationalization. Very improbable without this feature.

  • 2
    I don't know why your suggested answer started with my question and finishes with something related to directories creation. – Valerio Bozz Nov 21 '16 at 15:01
  • 1
    Hmm. Looks like that user originally posted a use of printf for creating a mkdir command, the edited their post. I retracted my close vote. – muru Nov 21 '16 at 15:05
1

You can't with bash. the POSIX specification of the printf utility doesn't support it either. You'd have to re-order the arguments by hand.

The printf (or print -f) builtins of ksh93 and zsh support them though:

$ printf '%2$s%1$s\n' a b
ba

GNU awk or perl also support it, so if you have any of those installed, in bash, you could redefine printf as a function like:

printf() { zsh -c 'printf "$@"' printf "$@"; }
  • Good to know that it's not a POSIX standard. Good workaround. – Valerio Bozz Dec 4 '16 at 18:07
0

This works for me:

set -- 'World' 'Hello'
printf '%s %s %s %s' "$2" "$2" "$1" "$1"
  • I don't think that this is more than an hardcoded workaround. The solution have to provide a way to choose how to display hardcoded arguments... without changing the order of the arguments, or repeating the arguments. – Valerio Bozz Dec 4 '16 at 18:59
  • @ValerioBozz You have the right to have an opinion. Even if incorrect. – sorontar Dec 4 '16 at 22:59
  • I don't know if you are serious. In any case I've added the question context just now. – Valerio Bozz Dec 6 '16 at 7:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.