View on GitHub

Computational Techniques for Life Sciences

ARRAYS

Both these ARGUMENT values as well as STRINGS are examples of ARRAYS: indexed collections of elements sharing a common name.

Array values

The ways to enter and access array values are similar to those used for command line arguments. The index is indicated with [] after the variable name. Generally, arrays must also be surrounded by {} when reporting element values.

prompt> val[1]=55 ; val[2]=72
prompt> mult=$(( ${val[1]} * ${val[2]})) ; echo $mult
3960

We can directly assign values to individual elements:

prompt> fruit[1]="apple"

or we use a () to assign them in batch:

prompt> fruit=(apple pear plum)

Arrays, like STRINGS, start counting at 0, so fruit[0] equals “apple”.

Batch assignment is particularly useful for making lists:

prompt> touch actin.fa myosin.fa ssb.fa
prompt> filelist=($(/bin/ls *.fa))

### use ${#array[@]} Number of elements in array.

prompt> echo There are ${#filelist[@]} fasta files: ${filelist[@]}
There are 3 fasta files: actin.fa myosin.fa ssb.fa
prompt> echo ${filelist[2]}
ssb.fa
prompt> echo "length of element 1 :" ${#filelist[1]}
length of element 1 : 9

### use ${array[@]:position:range} to select limited elements
prompt> array_count=( one two three four five six )
prompt> echo ${array_count[@]:1:2}
two three
prompt> echo ${array_count[@]:(-3):2}
four five

As with strings, read can likewise be used to input elements of an array:

prompt> declare -a newA
prompt> echo -n 'Enter >3 values:' ; read -a newA
pickle fly pyramid<return>
prompt> echo "newA has ${#newA[@]} elements:" ${newA[@]}
newA has 3 elements: pickle fly pyramid


Prev ARGUMENTS | Next BASH scripting | UP : BASH scripting | Top : Course Overview © 2017 Texas Advanced Computing Center