Reputation: 45
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
Upvotes: 1
Views: 417
Reputation: 33317
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
Upvotes: 1
Reputation: 23850
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.
Upvotes: 2