Bash: Repeated tasks with seq and for loops

Written by Benjamin Cane on 2011-08-04 | 1 min read

There comes a time where every sysadmin needs to execute the same task multiple times. Whether you need to create 12,000 2MB files, create multiple users, or simply delete more then 50k files at a time; for loops will save you time and typing.

For the instances where you need to execute a for loop a specific amount of times you can use seq to your advantage.

Today's example will show you how to create multiple files.

Example:

[email protected]:~$ for x in `seq 1 1 10`; do touch test.$x.txt; done  
[email protected]:~$ ls -la test.*  
-rw-r--r-- 1 bcane bcane 0 2011-08-03 14:31 test.10.txt  
-rw-r--r-- 1 bcane bcane 0 2011-08-03 14:31 test.1.txt  
-rw-r--r-- 1 bcane bcane 0 2011-08-03 14:31 test.2.txt  
-rw-r--r-- 1 bcane bcane 0 2011-08-03 14:31 test.3.txt  
-rw-r--r-- 1 bcane bcane 0 2011-08-03 14:31 test.4.txt  
-rw-r--r-- 1 bcane bcane 0 2011-08-03 14:31 test.5.txt  
-rw-r--r-- 1 bcane bcane 0 2011-08-03 14:31 test.6.txt  
-rw-r--r-- 1 bcane bcane 0 2011-08-03 14:31 test.7.txt  
-rw-r--r-- 1 bcane bcane 0 2011-08-03 14:31 test.8.txt  
-rw-r--r-- 1 bcane bcane 0 2011-08-03 14:31 test.9.txt  

Why it works

The command seq will output numbers based on the criteria you give it. The first number you provide seq is the number you want to start with, the second is the number you want to increment by. For example if you put seq 1 2 10 you would get an output of 1, 3, 5, 7, & 9. The last number in the list is the number you want to end with, as you can see from my 1 2 10 example if 10 is not the last number in the increment it will stop on the number before.

[email protected]:~$ seq 1 2 10  
1  
3  
5  
7  
9  
[email protected]:~$ seq 1 1 10  
1  
2  
3  
4  
5  
6  
7  
8  
9

Picture of Benjamin Cane

Benjamin's specialty is keeping the lights on for mission critical systems. He is currently building applications that enable high concurrency financial transactions.

Recently Benjamin published his first book; Red Hat Enterprise Linux Troubleshooting Guide. In addition to writing, he has several Open Source projects focused on making Ops easier. These projects include Automatron, a project enabling auto-healing infrastructure for the masses.


Publications

Identify, capture and resolve common issues faced by Red Hat Enterprise Linux administrators using best practices and advanced troubleshooting techniques

What people are saying:
Excellent, excellent resource for practical guidance on how to troubleshoot a wide variety of problems on Red Hat Linux. I particularly enjoyed how the author made sure to provide solid background and practical examples. I have a lot of experience on Red Hat but still came away with some great practical tools to add to my toolkit. - Amazon Review