Click to See Complete Forum and Search --> : Repeating a portion of my shell script X times


pwharff
10-09-2003, 03:41 AM
Ok, I am almost done with a shell script that I have been working on. Instead of posting in my previous thread, I thought I would create a new one since it's a little bit off from the previous topic.

My question is easy:

How do I repeat just a specific portion of my script a certain number of times and then when done repeating, continue on with the rest of the script?

Thanks a lot in advance. I'm learning!

jrbush82
10-09-2003, 06:32 AM
Howdy, I know nothing about shell scripting, but in C++ I would just write a for next loop like so:

for (int i = 0; i < NUMBER; i++) {
do stuff here;
}

Advanced Bash-Scripting Tutorial
http://www.tldp.org/LDP/abs/html/

pwharff
10-09-2003, 12:50 PM
Could you explain your loop? I'm not sure what a couple of items there mean (such as i)?

ph34r
10-09-2003, 01:15 PM
Actually, that syntax is for c/c++/javascript/php/etc. For a bash shell script, use

for i in `seq 1 10`
do
your repeating script snippet here
done

Change the 10 to however many times you want it to run.

pwharff
10-09-2003, 01:30 PM
Thanks a bunch ph34r!

Is it possilbe if you could explain what these options mean "i in `seq 1"

Also, I was looking up in my book and I found the "for" and "while" commands. What reason would I use "for" versus the "while" command?

This is what I found in my book:


i=0
while
[ $i -lt 100 ]
do
commands
done


Although, the thing I am the most frusterated with most of the time with linux/unix is I don't understand what the options are. The book didn't even explain what "-lt" meant. I just want to learn what everything means so that it can "stick" if you know what I mean.

pwharff
10-09-2003, 02:33 PM
I found the answer to my own question. The "-lt" is a "Test Operator"

Here are some Test Operators:


-eq Equal
-ne Not equal
-lt Less than
-le Less than or equal to
-gt Greater than
-ge Greater than or equal to



Although I'm still not exactly sure what the "i" is in the "for" loop (I figured out the seq command).

kam
10-09-2003, 03:23 PM
i is just a variable used as the counter.

ph34r
10-09-2003, 03:39 PM
Yah, the i is a variable, used as a counter.

When you surround a command with back ticks ` (the same key as ~), it executes that and puts the output where the command is. So in reality, that script is

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

You will get

1
2
3
...
10


Take a look at the bash programming cheat sheet here on the site (link at top with the rest of the nhfs).

pwharff
10-10-2003, 04:09 AM
Thanks again for all your help. I looked for the bash cheat sheet and couldn't find it, any help?