View on GitHub

Computational Techniques for Life Sciences

WHILE

Purpose

Continuous repeat commands until a condition is met. A while loop is useful in situations where the number of loop repetitions is not known beforehand

Syntax

while [ test condition ]
do
   ACTIONS
done

OR

while [ test condition ] ; do ACTIONS ; done;
prompt>  step=5 ; count=87; threshold=8
prompt> while (( $count >= $threshold )) ; do echo $count; (( count-=${step} )) ; done
87
82
77
72
67
62
57
52
47
42
37
32
27
22
17
12

Exercise

Recall that the read function store a line of text in a variable. Combine a while loop with the read function to write a bash script that counts residues in the PDB file 2a42.pdb.

First, download 2a42.pdb:

prompt> curl -o 2a42.pdb https://files.rcsb.org/download/2a42.pdb

prompt> vi cnt_res.sh
#!/bin/bash
# save filename, residue, and atom from the ARGUMENTS
file=$1 ; rsn=$2 ; atn=$3

# use `grep` to pull out the `ATOM` lines from the file
# use a while loop to read each line
# increment counter if residue and atom match the desired ARGUMENTS

( grep "ATOM" $file | while read line ;
   do
     aline=( $line ) ;
     res=${aline[3]} ;
     atm=${aline[2]};
     if [[ $atm == $atn ]] && [[ $res == $rsn ]]  ;
       then (( ++rscnt )) ;
     fi ;
     echo $rscnt ;done ; ) | tail -n 1
prompt> ./cnt_res.sh 2a42.pdb HIS CA
13


Prev IF/THEN | Next FOR LOOPS | UP BASH scripting | Top : Course Overview © 2017 Texas Advanced Computing Center