how to manipulate array in shell script

2020-06-18 02:52发布

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

标签: linux shell
3条回答
等我变得足够好
2楼-- · 2020-06-18 03:26

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
查看更多
姐就是有狂的资本
3楼-- · 2020-06-18 03:29

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.

查看更多
我命由我不由天
4楼-- · 2020-06-18 03:42

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

files+=( "$file" )
查看更多
登录 后发表回答