- This topic has 4 replies, 1 voice, and was last updated 8 years, 8 months ago by .
Viewing 4 reply threads
Viewing 4 reply threads
- You must be logged in to reply to this topic.
› Forums › Basic skills › Programming › Shell scripting (in bash) › Loops
How to construct various types of loop
The basic loop around a fixed set of values looks like this:
for X in 1 2 3 do echo The value of X is ${X} done
where the values are actually strings, so we can also have
for X in 34 b purple c 99 a do echo The value of X is ${X} done
or
for FRUIT in apples oranges pears do echo The current fruit is ${FRUIT} done
To loop around a range of numerical values, you can use
for X in {1..10} do echo The value of X is ${X} done
A more flexible way is to use the seq command which allows you to control the increment step size, use non-integer values, and control the format in which the number is printed
for X in $(seq 1 10) do echo The value of X is ${X} done
or
for X in $(seq -w 1 0.5 6) do echo The value of X is ${X} done
and so on. Type ‘man seq’ at a bash prompt to read the manual for the seq command.
You might want to load the list of values from a file:
for X in `cat myfile.scp` do echo The value of X is ${X} done
where myfile.scp is a plain text file with one value per line. This is a good way to loop around a list of files, for example.
You could use a loop to construct a string (e.g., in order to pass it as a command line argument):
S="" for X in `cat myfile.scp` do S=${S}" -I "${X} done echo $S # ... now do something useful with ${S}
where myfile.scp is a plain text file with one value per line.
Some forums are only available if you are logged in. Searching will only return results from those forums if you log in.
Copyright © 2024 · Balance Child Theme on Genesis Framework · WordPress · Log in