Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikibooksThe Free Textbook Project
Search

Bash Shell Scripting/Loops

From Wikibooks, open books for an open world
<Bash Shell Scripting
Conditional ExpressionsBash Shell Scripting
Loops
Shell Functions

Often we want to run the same sequence of commands, over and over again, with slight differences. For example, suppose that we want to take all files named*.txt and rename them to*.txt.bak ("backup"). We can use file-expansion to get the list of files named*.txt, but how do we use that list? There's no obvious command containing, say,'foo.txt' 'bar.txt' 'baz.txt', that would perform the three moves we need. What we need is afor loop:

forfilein*.txt;domv"$file""$file.bak"done

The above takes the variablefile, and assigns it in turn to each word in the expansion of*.txt. Each time, it runs the body of the loop. In other words, it is equivalent to the following:

file='foo.txt'mv"$file""$file.bak"file='bar.txt'mv"$file""$file.bak"file='baz.txt'mv"$file""$file.bak"

There is nothing special here about filename expansion; we can use the same approach to iterate over any other argument-list, such as the integers 1 through 20 (using brace expansion):

foriin{1..20};doecho"$i"done

or the positional parameters"$@":

forargin"$@";doecho"$arg"done

In fact, that specific case is so common that Bash provides the equivalent shorthandforarg;do, within"$@" being implied. (But it's probably better to use the explicit form anyway.)

Another kind of loop is thewhile loop. It is similar to anif statement, except that it loops repeatedly as long as its test-command continues to be successful. For example, suppose that we need to wait until the filewait.txt is deleted. One approach is to "sleep" for a few seconds, then "wake up" and see if it still exists. We can loop repeatedly in this fashion:

while[[-ewait.txt]];dosleep3# "sleep" for three secondsdone

Conversely, we can use anuntil loop to loopuntil a given command is successful; for example, the reverse of the above might be:

until[[-eproceed.txt]];dosleep3# "sleep" for three secondsdone

Of course, this is the same as combiningwhile with!, but in some cases it may be more readable.

  • Just likeif,while judgestrue orfalse in the same way. Try it out yourself.
Retrieved from "https://en.wikibooks.org/w/index.php?title=Bash_Shell_Scripting/Loops&oldid=4085703"
Category:
Hidden category:

[8]ページ先頭

©2009-2025 Movatter.jp