Home > database >  how bash shell script construct array element with space [duplicate]
how bash shell script construct array element with space [duplicate]

Time:09-28

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?

CodePudding user response:

The code a="'1 2' '3 4'" does not create an array, it creates a string with embedded single-quotes.

$: a="'1 2' '3 4'"
$: echo "[$a]"
['1 2' '3 4']

If you want to create an array, you have to use the right syntax.

$: a=( '1 2' '3 4' )
$: printf "[%s]\n" "${a[@]}"
[1 2]
[3 4]

Then if you want to copy it to another array, just treat it like an array instead of a string.

b=( "${a[@]}" )
printf "[%s]\n" "${b[@]}"
[1 2]
[3 4]

To convert the string created in a="'1 2' '3 4'" to an array is a little trickier.

IF you know that the format is a consistent match for the above, try this:

$: echo "[$a]"
['1 2' '3 4']
$: IFS='#' read -ra b < <( sed -E "s/'  '/#/g; s/ *' *//g" <<< "$a" )
$: printf "[%s]\n" "${b[@]}"
[1 2]
[3 4]

but generally, this is a bad plan. Try to fix your input!

CodePudding user response:

use quotas in your echo command, when you call value, like this:

echo "$a"

b="$a"
  • Related