Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to manipulate array in shell script

Tags:

linux

shell

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
like image 777
vijay.shad Avatar asked Feb 28 '10 20:02

vijay.shad


People also ask

How do I modify an array in bash?

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.

Can we use array in shell script?

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.

How array is used in shell script with example?

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.


1 Answers

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.

like image 146
Enrico Carlesso Avatar answered Nov 12 '22 03:11

Enrico Carlesso