Thursday, December 15, 2005

Command Substitution for Counted Loops

Here's a loop.

for i in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
do
echo $i
done

Here's another way to do the same thing:

for i in $(seq 20)
do
echo $i
done
Just the command seq 20 by itself spits out the sequence 1 .. 20 . (Try it.)

The expression $(command) says "Run command in a subshell,
substitute its output for the expression, and then run the resulting command in the current shell."

This is called command substitution

Since "$" marks variables, think of $(command) as "The value of the temporary variable containing the output of the subshell '(command)'"

You have a mystery version of foo.c and you want to know what archival version it's closest to?

for i in $(seq 10 -1 1)
do
cvs co -p -r1.$i foo.c | diff - foo.c | wc -l
done
The version with the smallest diff is the version you're looking for.

If you have a very large number of versions, you can pipe the loop's output through less. Alternatively, if you're using a terminal emulator, you can use the scroll bar to scroll back up the screen, or, in kterm, the convenient Shift PgUp.

0 Comments:

Post a Comment

<< Home