1

I am trying to concatenate strings using array variable but getting error.

declare -a arr
arr=(one two three)
var= "${arr[0]}    ${arr[1]}"
echo $var

expected output

one    two

(4 spaces between one and two)

I am getting following error:-

[wasadmin@gblabvl31 IBM]$ ./test.sh
./test.sh: line 10: one     two: command not found

Does this mean we can't assign a variable with array element (used as a variable)? What is the other way to do this

2 Answers 2

2

You must remove the space after the =:

var="${arr[0]}    ${arr[1]}"

Bash supports a syntax that allows you to temporarily set a variable when you call a command. The syntax works like that VARNAME=somevalue command. This will execute the command, having set the (environment) variable VARNAME to somevalue. If you say VARNAME= command then bash interprets that as VARNAME="" command i.e. sets the variable to the empty string. In your case, that causes bash to try to execute the "${arr[0]} ${arr[1]}" part as if it was a command.

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

Comments

1

You have an extra space in the assignment. Replace

var= "${arr[0]}    ${arr[1]}"
#   ^

with

var="${arr[0]}    ${arr[1]}"

You should also quote the argument of echo to preserve the whitespace in it

echo "$var"

The reason for the error message you see, is that when there is a space after the equal sign, bash interprets the command as assigning an empty environment variable named var, and then tries to execute the command "${arr[0]} ${arr[1]}" which is evaluated to one two, and thus the command not found error

Comments

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.