Reputation: 624
I discovered something weird in bash I can't explain. When I initialize an array using the bracket notation with a quoted string (single and double), the string is placed as the first element of the array. When I put the string in a variable and I do the same withe the variable, the string is split properly delimited by IFS.
#/bin/bash
test1="hello my name is mr nobody"
array1=($test1)
test2='hello my name is mr nobody'
array2=($test2)
array3=("Hello my name is mr nobody")
array4=('Hello my name is mr nobody')
declare -p array1
declare -p array2
declare -p array3
declare -p array4
The output:
declare -a array1='([0]="hello" [1]="my" [2]="name" [3]="is" [4]="mr" [5]="nobody")'
declare -a array2='([0]="hello" [1]="my" [2]="name" [3]="is" [4]="mr" [5]="nobody")'
declare -a array3='([0]="Hello my name is mr nobody")'
declare -a array4='([0]="Hello my name is mr nobody")'
What exactly happening, and what is different between the two methods?
Upvotes: 1
Views: 315
Reputation: 241931
There is no difference between a string and a string in a variable. Consequently, the following two are identical:
> test1="hello my name is mr nobody"
> array1=($test1)
> array2=(hello my name is mr nobody)
So are the following two:
> test2="hello my name is mr nobody"
> array3=("$test2")
> array4=("hello my name is mr nobody")
The string does not "remember" that some or all of its characters were quoted. The quotes are entirely syntactic, and are interpreted (once) by the bash interpreter.
This is not significantly different from other languages: in C or Python, the string "abc"
has three characters, not five; the quotes were only used to indicate that the literal is a string. In bash, however, it is possible (sometimes) to write a string without quotes, something not allowed by many other languages.
Word splitting is performed on unquoted strings, so it is performed on $test1
and a string
, and not performed on the quoted versions "$test1"
and "a string"
.
Upvotes: 2