scripting

Björn Lindberg d95-bli at nada.kth.se
Tue Jul 13 04:10:01 PDT 2004


Shane Shields <silashields at ttnet.net.tr> writes:

> On Monday 12 July 2004 10:05 pm, Jason Kircher wrote:
> > for i in file.{1,2,3,4} ; do echo $i ; done
> locutus:~$ for i in file.{1,2,3,4} ; do echo $i ; done
> file.1
> file.2
> file.3
> file.4
> locutus:~$ for i in file.`seq 1 4` ; do echo $i ; done
> file.1
> 2
> 3
> 4
> 
> ;)

The way to think about these matters is to distinguish the expansion
times from the actual execution. The first example above expands into

  for i in file.1 file.2 file.3 file.4; do echo $i ; done

(Why? Because that is what { ... , ... , ... } do.)

The second example expands (via command substitution) into

  for i in file.1 2 3 4; do echo $i ; done

These expansions occur /before/ actual evaluation. I'm sure Shane and
others are well aware of this, I just wanted to point it out since I
didn't see it mentioned elsewhere in the thread.

> locutus:~$ for i in `seq 1 4` ; do echo file.$i ; done
> file.1
> file.2
> file.3
> file.4
> 
> Of course these only work for a sequence of files with the same name. 
> But wait.....Theres more!!!
> 
> locutus:~$ for i in `seq 1 4` `seq 11 14` ; do touch file.$i ; done

And since we are using `seq' which is not very common on Unix systems
other than Linux (that I know of), we might as well use features
specific to POSIX shells as wekll as being a bit more familiar to C
programmers perhaps:

bjorn at nex:~> for((i=1; i<=14; i==4 ? i=11 : i++)); do echo file.$i; done
file.1
file.2
file.3
file.4
file.11
file.12
file.13
file.14

;-)


Björn



More information about the lfs-chat mailing list