Monday, October 16, 2017

BASH For Loop Sequence

Here are a few different ways to do a loop over a range of numbers:

for I in {1..10}; do echo $I; done

for I in 1 2 3 4 5 6 7 8 9 10; do echo $I; done

for I in $(seq 1 10); do echo $I; done

for ((I=1; I <= 10 ; I++)); do echo $I; done

numbered hostnames padded with zeros:
for ((I=1; I <= 29 ; I++)); do
echo `printf "node%02d\n" $I`;
done

###

If I need to create lots of files with similar names or to use up lots of space for testing, then I do things like:

for f in 0 1 2 3 4 5 6 7 8 9
do
for g in 0 1 2 3 4 5 6 7 8 9
do
dd if=/dev/zero of=/some/path/file0$f$g bs=16384 count=xxxx
done
done

It is a quick and compact way to get the job done.

###

These are very useful examples to see side by side. Thanks, Gavin!

I'd just like to add 2 points:

1. for i in $(seq 1 10);

can be simplified to

for i in $(seq 10);

2. Older versions of BASH do not have the 'seq' command or brace {1..10} support , which makes the C form(a) the most portable, particularly when going back and forth between UNIX and Linux.

---------
(a) C form: for ((I=1; I <= 10; I++));

###


No comments:

Post a Comment