Search code examples
bashquoting

Bash, get normal strings to behave like $@ vs $*


Solution:

I eventually got it with bash arrays, my solution is here.


Question:

In bash, I can have a function whose arguments have spaces, and I can use $@ or $* to get the quoting right:

$ _() { ruby -e 'p ARGV' "$@"; }; _ 'a b c' '1 2 3'
["a b c", "1 2 3"]

$ _() { ruby -e 'p ARGV' "$*"; }; _ 'a b c' '1 2 3'
["a b c 1 2 3"]

I'm building up a string where the arguments could have spaces, and would like it to behave like the "$@", is there a way to do this?

$ arg1="a b c"
$ arg2="1 2 3"
$ args="$arg2 $arg2"

# behaves like $*, but I want it to behave like $@
$ ruby -e 'p ARGV' "$args"
["1 2 3 1 2 3"]

$ ruby -e 'p ARGV' $args
["1", "2", "3", "1", "2", "3"]

Solution

  • Absolutely, use arrays.

    $ args=()
    $ args+=("a b c")
    $ args+=("1 2 3")
    
    $ ruby -e 'p ARGV' "${args[@]}"
    ["a b c", "1 2 3"]