Search code examples
bashshellvariablesfor-looptail

BASH: Iterate range of numbers in a for cicle


I want to create an array from a list of words. so, i'm using this code:

for i in {1..$count} 
do
array[$i]=$(cat file.txt | cut -d',' -f3 | sort -r | uniq | tail -n ${i})
done

but it fails... in tail -n ${i}

I already tried tail -n $i, tail -n $(i) but can't pass tail the value of i

Any ideas?


Solution

  • It fails because you cannot use a variable in range directive in shell i.e. {1..10} is fine but {1..$n} is not.

    While using BASH you can use ((...)) operators:

    for ((i=1; i<=count; i++)); do
       array[$i]=$(cut -d',' -f3 file.txt | sort -r | uniq | tail -n $i)
    done
    

    Also note removal of useless use of cat from your command.