1

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?

1
  • You are not quoting the string. Use array1=( "$test1" ) Commented May 8, 2015 at 18:28

1 Answer 1

2

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".

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I was confused by the unquoted strings I think.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.