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/lau开发者_StackOverflow社区nchers/join_files.sh: 51: [0]: not found
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.
To add an element to the end of an array, use the += operator (since bash 3.1 in 2004):
files+=( "$file" )
you can write it this way as well
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
fi
To: Vijay
tiny demonstration, list *.txt files in directory and put to array FILES
declare -a FILES
i=0
for file in *.txt
do
FILES[((i++))]=$file
done
# display the array
for((o=0;o<${#FILES};o++))
do
echo ${FILES[$o]} $o
done
output
$ ./shell.sh
A.txt 0
B.txt 1
file1.txt 2
file2.txt 3
file3.txt 4
精彩评论