Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell Script: correct way to declare an empty array

Tags:

arrays

bash

shell

I'm trying to declare an empty array in Shell Script but I'm experiencing an error.

#!/bin/bash  list=$@  newlist=()  for l in $list; do          newlist+=($l)  done  echo "new" echo $newlist 

When I execute it, I get test.sh: 5: test.sh: Syntax error: "(" unexpected

like image 611
luizfzs Avatar asked Sep 20 '13 16:09

luizfzs


People also ask

What is the correct way of declaring an empty array?

The syntax of declaring an empty array is as follows. data-type[] array-name = new data-type[size]; //or data-type array-name[] = new data-type[size];

How do you declare an empty variable in shell script?

To find out if a bash variable is empty: Return true if a bash variable is unset or set to the empty string: if [ -z "$var" ]; Another option: [ -z "$var" ] && echo "Empty" Determine if a bash variable is empty: [[ ! -z "$var" ]] && echo "Not empty" || echo "Empty"

How do you declare an array in a script?

Declaring Arrays: Notice the uppercase and lowercase letter a. Uppercase A is used to declare an associative array while lowercase a is used to declare an indexed array. The declare keyword is used to explicitly declare arrays but you do not really need to use them.


2 Answers

Run it with bash:

bash test.sh 

And seeing the error, it seems you're actually running it with dash:

> dash test.sh test.sh: 5: test.sh: Syntax error: "(" unexpected 

Only this time you probably used the link to it (/bin/sh -> /bin/dash).

like image 94
konsolebox Avatar answered Sep 24 '22 00:09

konsolebox


I find following syntax more readable.

declare -a <name of array> 

For more details see Bash Guide for Beginners: 10.2. Array variables.

like image 45
shaffooo Avatar answered Sep 23 '22 00:09

shaffooo