How to manipulate an array in a shell script

I want my script to define an empty array. array values ​​must be added if the specified condition becomes true. for this i did it

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 I run this script, I get some error similar to this

 linux-softwares/launchers/join_files.sh: 51: [0]: not found 
+5
source share
3 answers

When the settings data in the array are not displayed 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 can see, a small modification of $ (()) for the mathematical operation, but the FILES assignments are the same ...


As noted after many tests, Ubuntu, by default, seems to be the dash that caused the error.

+3
source

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

 files+=( "$file" ) 
+1
source

you can also record it in the same way

 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 demo, list * .txt files in a directory and put into FILES array

 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 

Exit

 $ ./shell.sh A.txt 0 B.txt 1 file1.txt 2 file2.txt 3 file3.txt 4 
0
source

Source: https://habr.com/ru/post/918192/


All Articles