what is wrong in this bash expression

145 Views Asked by At

I got one error in the first expr

nmin =$(expr ($nr-1)*31)
nmax =$(expr ($nr*31)-1)    
array=`ls *d03_*`   # specify files to be subsetted
for name in ${array[@]:nmin:30}

After reading the documentation seems like one space or really minor thing is creating the error

Also i don t know is the slicing in for is correct .

2

There are 2 best solutions below

9
On

An array definition needs round parenthesis.

This assigns a string to the variable x:

x=`echo $? $$`
echo "$x"

This assigns two values to an array:

x=(`echo $? $$`)
echo "${x[@]}"
0
On

You have several errors in your code. First, you cannot put whitespace before or after the = in an assignment statement.

nmin=$(expr ($nr-1)*31)
nmax=$(expr ($nr*31)-1)   

Second, expr is not needed for arithmetic; the shell can do that itself.

nmin=$(( ($nr-1)*31 ))
nmax=$(( ($nr*31)-1 ))

Third, the proper way to assign an array is with parentheses

array=( `ls *d03_*` ) 

Fourth, it's never appropriate to use ls like this. Just expand the glob directly into the array:

array=( *d03_* )

Your for loop is actually almost correct; you should, however, quote the expansion so that any whitespace in each array element is preserved.

for name in "${array[@]:nmin:30}"; do

which iterates over ${array[nmin]} through ${array[nmin+29]}.