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
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];
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"
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.
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).
I find following syntax more readable.
declare -a <name of array>
For more details see Bash Guide for Beginners: 10.2. Array variables.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With