View on GitHub

Computational Techniques for Life Sciences

FOR

Purpose

repeat commands for each element of a list OR repeat commands over a range

Syntax

for arg in [list]
do
 command(s)...
done

OR

for((index=start;index test condition; increment index)
do
 command(s)...
done
## FOR OVER LIST
prompt> for fruit in apple pear banana orange ; do echo $fruit ; done;
apple
pear
banana
orange

## FOR OVER RANGE
prompt> for((i=1;i<=12;++i)); do echo $i; done;
1
2
3
4
5
6
7
8
9
10
11
12

Exercise

Use a FOR loop to create 10 files, fake-1.txt -> fake-10.txt . Use a second FOR loop to rename the files from to real-1.txt -> real-10.text.

vi for_name.sh
#!/bin/bash
prefix="fake";
for((i=1;i<=10;++i));
   do
     touch ${prefix}-${i}.txt ;
   done;
ls ${prefix}*txt ;

newprefix="real";
for file in ${prefix}*txt ;
  do
    mv ${file} ${file/${prefix}/${newprefix}} ;
  done;
ls ${newprefix}*.txt
prompt> chmod +x for_name.sh
prompt> ./for_name.sh
0 fake-1.txt   0 fake-2.txt   0 fake-4.txt   0 fake-6.txt   0 fake-8.txt
0 fake-10.txt  0 fake-3.txt   0 fake-5.txt   0 fake-7.txt   0 fake-9.txt

0 real-1.txt   0 real-2.txt   0 real-4.txt   0 real-6.txt   0 real-8.txt
0 real-10.txt  0 real-3.txt   0 real-5.txt   0 real-7.txt   0 real-9.txt


Prev WHILE LOOPS | Next CASE STATEMENTS | UP : BASH scripting | Top Course Overview © 2017 Texas Advanced Computing Center