how to manipulate array in shell script

2020-06-18 03:24发布

问题:

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

回答1:

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.



回答2:

To add an element to the end of an array, use the += operator (since bash 3.1 in 2004):

files+=( "$file" )


回答3:

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


标签: linux shell