0

I am trying to run a bash -c command relying on the parent bash scripts arguments via "$@"

When running a normal command, I use "$@" and bash does the expand magic for each arg.

printf '[%s] [%s]\n' "$@"
$ ./script one "t w o"
[one] [t w o]

My first naive attempt at escaping falls over in an odd way with the $@ quotes as the parent bash appears to the "end" the current argument.

bash -c "printf '%s %s\n' \"$@\""
$ ./script one "t w o"
t w o": -c: line 1: unexpected EOF while looking for matching `"'
t w o": -c: line 2: syntax error: unexpected end of file

From there "$@" kind of defies my regular escaping tricks as nothing is really quoted, I'm guessing bash deals with the expansion at a lower exec level.

How do I use the "$@" script arguments in a bash -c one liner?

Matt
  • 8,841
  • 1
  • 26
  • 32

1 Answers1

2

To avoid escaping, use "$@" as normal and pass "$@" to the parent bash -c including a dummy argument for $0.

bash -c 'printf "[%s] [%s]\n" "$@"' this-is-bash-dollar-zero "$@"
$ ./script one "t w o"
[one] [t w o]
Matt
  • 8,841
  • 1
  • 26
  • 32
  • 3
    In many cases [`--` is special](https://unix.stackexchange.com/q/11376/108618), but not here.`bash` stops detecting options after the option-argument to `-c`. Whatever follows becomes `$0`, `$1`, etc. With `--` there `bash -c` simply takes *this string* as `$0`. It makes sense to place a meaningful string there because `$0` is used in error messages.(try `bash -c if --` vs `bash -c if my-special-purpose-bash`). – Kamil Maciorowski Apr 23 '21 at 05:31
  • 2
    IOW, you should use `bash -c 'inline script' helpful-name-for-my-inline-script arg1 arg2...` or just `bash -c 'inline script' bash arg1 arg2...`, not `bash -c 'inline script' -- arg1 arg2...` as `--` is a very confusing name for your *inline script*. – Stéphane Chazelas Apr 23 '21 at 07:22
  • oic, I assumed it was the usual `--` – Matt Apr 23 '21 at 07:37