Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash array: Unexpected Syntax error [closed]

I am writing this simple bash script as follows.

#!/bin/bash

array=( /home/abc/Downloads/something.bat /home/abc/Downloads/smb.conf )
echo ${array[@]}

I expected it to print all the names of the files in the array. But I get this error instead:

test.sh: 3: Syntax error: "(" unexpected

If I change the declaration of array to

array = {/home/abc/Downloads/something.bat /home/abc/Downloads/smb.conf}

this error goes away but I still have new errors

test.sh: 3: array: not found
test.sh: 4: Bad substitution

How can I resolve this issue? This is my first time in shell programming so I am unable to fix the issues myself.

RESOLVED:

I was executing it as sh test.sh but I forgot I had to execute it as bash test.sh

like image 813
user1357576 Avatar asked Jun 14 '12 03:06

user1357576


2 Answers

Variable assignments can't have a space around the = sign:

array=( /a/b/  /c/d )
     ^--no spaces 

are you sure?

marc@panic:~$ array =(a b)      
bash: syntax error near unexpected token `('
marc@panic:~$ array= (a b)  
bash: syntax error near unexpected token `('
marc@panic:~$ array = (a b)
bash: syntax error near unexpected token `('
marc@panic:~$ array=(a b)  
marc@panic:~$ echo ${array[1]}
b
like image 131
Marc B Avatar answered Sep 21 '22 08:09

Marc B


Pointer: Spaces are important with variable assignment in BASH. Don't use them before or after the equal sign.

like image 25
Chad WALSTROM Avatar answered Sep 21 '22 08:09

Chad WALSTROM