I want my script to define an empty array. array values should be added if predefined condition gets true. for this what i have done is
declare -a FILES
file_count=0
if [ "$file_ext" != "$SUPPORTED_FILE_TYPE" ] ; then
echo "$file_ext is not supported for this task."
else
$FILES[$file_count] = $filename
file_count=$file_count+1
fi
when executing this script i am getting some error like this
linux-softwares/launchers/join_files.sh: 51: [0]: not found
To update element of an array in Bash, access the element using array variable and index, and assign a new value to this element using assignment operator.
There are two types of arrays that we can work with, in shell scripts. The default array that's created is an indexed array. If you specify the index names, it becomes an associative array and the elements can be accessed using the index names instead of numbers.
Shell supports a different type of variable called an array variable. This can hold multiple values at the same time. Arrays provide a method of grouping a set of variables. Instead of creating a new name for each variable that is required, you can use a single array variable that stores all the other variables.
When settings data in array does not recall with $:
declare -a FILES
file_count=0
if [ "$file_ext" != "$SUPPORTED_FILE_TYPE" ] ; then
echo "$file_ext is not supported for this task."
else
FILES[$file_count]=$filename
file_count=$file_count+1
fi
FILES without $.
This works for me:
#!/bin/bash
declare -a FILES
file_count=0
file_ext='jpg'
SUPPORTED_FILE_TYPE='jpg'
filename='test.jpg'
if [ "$file_ext" != "$SUPPORTED_FILE_TYPE" ] ; then
echo "$file_ext is not supported for this task."
else
FILES[$file_count]=$filename
file_count=$(($file_count+1))
fi
As you see, a little modification $(( )) for math operation, but the FILES assignements is the same...
As pointed out after lots of tests, Ubuntu default shell seems to be dash, which raised the error.
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