User Tools

Site Tools


linux:bash_for_loop

USING FOR LOOP IN BASH

13.10.2009

Let's assume we have Folder1, Folder2, Folder3, each of them with some multiple rar archives

ls Folder1
archive.rar archive.r01 archive.r02
 
ls Folder2
archive.rar archive.r01 archive.r02
 
ls Folder3
archive.rar archive.r01 archive.r02

We want to extract archives content into a temporary dir, let's say /tmp/extracted_files.
We can do this manually, by entering each directory and issuing manually the extraction command, or we can use for…do done construction:

for i in 1 2 3
do
   unrar e Folder$i/archive.rar /tmp/extracted_files
done

or in a single line:

for i in 1 2 3; do unrar e Folder$i/archive.rar /tmp/extracted_files; done

For a few elements, enumeration of 1, 2, 3… is quicker, but what about 100 elements? We can save us big time using seq:

for i in $(seq 1 100)
do
   unrar e Folder$i/archive.rar /tmp/extracted_files
done

The syntax for seq is
seq LAST
seq FIRST LAST
seq FIRST INCREMENT LAST

Starting with bash 3.0, there is built-in support for ranges:

for i in {1..5}
do
 ...

linux/bash_for_loop.txt · Last modified: 2013/03/16 17:40 (external edit)