Shell – “$@” expansion for user defined variables

bourne-shellquotingshellshell-scriptvariable

I'm trying to get a (bourne shell) variable to expand like "$@" so it produces multiple words with some having preserved spaces. I've tried defining the variable in many different ways but still can't get it to work:

#!/bin/sh

n=\"one\ two\"\ three
for i in "$n"; do
echo $i
done

I want to define the variable so the script outputs one two first and then three next iteration, which is what you'd get if you replaced the quoted variable with "$@" and passed 'one two' three as the arguments.

Is "$@" just magic?

Best Answer

So bourne shell (IIRC) doesn't support arrays. You can still use "$@"

set -- "one two" three
for i in "${@}" ; do
    echo "$i"
done

Outputs:

one two
three

Tested on AIX 7.1 bsh.

Related Question