2

I have a function in bash that accepts unknown amount of arguments:

printAndRunCommand() {
  printf "$@"
  eval "$@"
}

Because printf accept only single argument, when I run this command with

printAndRunCommand wget stackoverflow.com 

only wget gets printed. I can archive the same effect using echo command, but I use printf specific characters like color change, in origin command looks like printf '"\033[4;36m$@\e[0;33;40m".

How do I pass "$@" to printf command?

deathangel908
  • 8,601
  • 8
  • 47
  • 81
  • those `\033[4;36m` are ANSI escape code and is no way related to printf. Just embed the escape character directly, or use `\033`/`\e` and use `echo -e` to make it escape special characters. [How to change the output color of echo in Linux](https://stackoverflow.com/q/5947742/995714) – phuclv May 12 '19 at 11:38

1 Answers1

5

Use $* to turn the list of arguments into a single string.

printf '%s\n' "$*"

Better yet, use %q to quote metacharacters.

printf '%q ' "${@}"; printf '\n'
$ printAndRunCommand 'a b' c 'foo$bar'
a\ b c foo\$bar

If you've got bash 4.4+ you can use @Q for nicer looking output that's still properly quoted.

printf '%s\n' "${*@Q}"
$ printAndRunCommand 'a b' c 'foo$bar'
'a b' 'c' 'foo$bar'
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • Thanks for the `@Q` reference, I haven't come across that before. I don't understand why the bash providers used `q` to mean `escaped` (despite them telling is it means "quoted", it clearly doesn't) and now are using a completely different approach outside of `printf` to really get `quoted` (we couldn't just have something like `%E` for escaped and `%Q` for quoted?) but I suppose we should all just be thankful something exists! – Ed Morton May 12 '19 at 21:20