Monday, August 06, 2007

Z Shell for loop -- UNIX zsh

Here is a succinct use of the for loop using the robust Z Shell. See ZSH is cool: Brace Expansion by St├ęphane Kattoor for background details. Here is a practical application of the zsh for loop.

Using the Bourne shell for loop
# sh
# for i in 1 2 3 4 5 6 7 8 9 10 11 12
rcp -p /etc/hosts esoftclient$i:/etc

Now using brace expansion for the Z shell for loop
# zsh
# for i in {1..12}
rcp -p /etc/hosts esoftclient$i:/etc

# zsh
# for i in {1..100}
rcp -p /etc/hosts esoftclient$i:/etc

As you can see in the aforementioned, this inline is short and to the point.


Stephane said...

Zsh is really worth reading its man page, as it is full of gems like this !

By the way, thanks for the backlink :-)

esofthub said...

I agree with you, and I'm going to take a closer look at it. You're welcome on the backlink -- it was worth it.

Anonymous said...

welcome back, I am now a fan


Cian said...

This works in Bash version 3+ as well.

esofthub said...

Rod, I was on a long overdue vacation...I needed a break from work, Internet, my website and blog --- well, I guess everything. Roy

Tarka said...

A more succinct version in bash is:

for i in `seq 12`; do

'seq' also has the ability to format the number (leading zeros, etc). However zsh is something I know I should investigate.

claudio said...

This is a cool trick.


Anonymous said...

What's special in this case ? ksh93 has ANSI-C-like for loops like
for((i=0;i<12;i++));do echo "snoopy $i";done

esofthub said...

anonymous, thank you for adding to the discussion

Anonymous said...

You can be even more faster in Zsh:

for i in {1..12} ; rcp -p /etc/hosts esoftclient$i:/etc

-mika- (

esofthub said...

mika, I've added you to my technical blogroll.

zzapper said...

# to repeat a command periodically
while true; do echo "infinite loop"; sleep 5; done

esofthub said...


I just wanted to a comment to but unfortunately I couldn't figure out, how to do this w/o registration. Perhaps you could post it:

It's Posted Manuel...

Tarka: 'seq' also has the ability to format the number (...)

Which zsh has, too :-)

zsh# print {1..10}
1 2 3 4 5 6 7 8 9 10
zsh# print {01..10}
01 02 03 04 05 06 07 08 09 10