「Transwiki:Bash Shell Scripting」の版間の差分

削除された内容 追加された内容
Fu7mu4 (トーク | 投稿記録)
Fu7mu4 (トーク | 投稿記録)
589 行
==反復・ループ==
 
いくどか、私達はすこしだけ変化させながら一連のコマンドを繰り返して実行したいときがあります。例えば、<tt>*.txt</tt>にあてはまる全てのファイルをとり、<tt>*.txt.bak</tt>に名前を変える場合("backup")を想定しましょう。私達はファイル名展開を使用して、<tt>*.txt</tt>の名前のあるファイルリストを取得できます。しかし、そのリストをどのように使えばよいのでしょう。明らかにコマンドは含まれていません。例えば、<tt>'foo.txt' 'bar.txt' 'baz.txt'</tt>とすると、これから3つを移動させる必要があります。これに必要なのは<tt>for</tt>ループです。
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 <tt>*.txt</tt> and rename them to <tt>*.txt.bak</tt> ("backup"). We can use file-expansion to get the list of files named <tt>*.txt</tt>, but how do we use that list? There's no obvious command containing, say, <tt>'foo.txt' 'bar.txt' 'baz.txt'</tt>, that would perform the three moves we need. What we need is a <tt>for</tt> loop:
 
<source lang="bash">for file in *.txt ; do
595 行
done</source>
 
上の例は、変数<tt>file</tt>をとり、<tt>*.txt</tt>の展開のそれぞれの単語が割り当てられます。そのときどきで、ループの本体を実行します。いいかえればこれは次のものと同じです。
The above takes the variable <tt>file</tt>, and assigns it in turn to each word in the expansion of <tt>*.txt</tt>. Each time, it runs the body of the loop. In other words, it is equivalent to the following:
 
<source lang="bash">file='foo.txt'