I want to construct array element with space, it works while run in command line:
pc:/tmp$ b=('1 2' '3 4')
pc:/tmp$ echo $b
1 2
pc:/tmp$ echo ${b[1]}
3 4
But it get the elements split with space in script:
pc:/tmp$ cat t.sh
a="'1 2' '3 4'"
echo $a
b=($a)
echo $b
echo ${b[1]}
echo ${b[2]}
pc:/tmp$ bash t.sh
'1 2' '3 4'
'1
2'
'3
I want to get '1 2' with echo $b as get '3 4' with ${b[1]} in script.
How could I achieve this?
And why it can't not works in script but works in command line?
b=($a)splits the string on white space. You would have to write a parser for yourato tear it apart.b=($a)at the command line it would behave just the same way as it did in your script. This isn't a script-vs-command-line difference.shlexmodule (if you want the closest possible accuracy to a real POSIX sh parser), orxargs printf '%s\0'(if you want something that's available everywhere and doesn't add more bugs than the minimum setxargsforces).