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

削除された内容 追加された内容
Fu7mu4 (トーク | 投稿記録)
Fu7mu4 (トーク | 投稿記録)
577 行
===可読性の注意===
 
上の例の<tt>if</tt> ステートメントは、人間や読みやすく理解しやすくなるようにフォーマットしています。これはこの本の例だけでなく現実世界のスクリプトでも重要です。特に上の例は次の規約に従っています。
The <tt>if</tt> statements in the above examples are formatted to make them easy for humans to read and understand. This is important, not only for examples in a book, but also for scripts in the real world. Specifically, the above examples follow these conventions:
 
* <tt>if</tt>ステートメント内のコマンドは一定量でインデントされています。(半角スペース2個で)。このインデントはBashとは関係ありません。-- Bashは行頭のホワイトスペースを無視します。-- しかしこれは人間のプログラマーにはとても重要です。インデントがない場合、<tt>if</tt> ステートメントの開始と終了がわからなくなり、また<tt>if</tt> ステートメントがあるかどうかもわからなくなります。一定のインデントは特に、<tt>if</tt>ステートメント内にネストした<tt>if</tt>ステートメント(や、あとで学ぶ他の制御構文)に重要です。
* <tt>then</tt>の前のセミコロン<tt>;</tt>を使用します。これはコマンドを分割する特別な演算子です。これは改行とほぼ同じですが、異なる点もあります。(例えば、コメントは<tt>#</tt>から行末までで、<tt>#</tt> から<tt>;</tt>までではありません。)私達は、<tt>then</tt>を次の行の行頭に書くこともでき、これは完全に合法です。単純なスクリプトでは十分でしょう。これは通常の構文が表われないように統一しましょう。しかし現実世界のスクリプトの場合プログラマーは通常<tt>if</tt> または <tt>elif</tt>の行の行末に<tt>; then</tt>を置くのでここではこの規約に従っています。
 
* The commands within an <tt>if</tt> statement are indented by a consistent amount (by two spaces, as it happens). This indentation is irrelevant to Bash — it ignores whitespace at the beginning of a line — but is very important to human programmers. Without it, it is hard to see where an <tt>if</tt> statement begins and ends, or even to see that there is an <tt>if</tt> statement. Consistent indentation becomes even more important when there are <tt>if</tt> statements nested within <tt>if</tt> statements (or other control structures, of various kinds that we will see).
* The semicolon character <tt>;</tt> is used before <tt>then</tt>. This is a special operator for separating commands; it is mostly equivalent to a line-break, though there are some differences (for example, a comment always runs from <tt>#</tt> to the end of a line, never from <tt>#</tt> to <tt>;</tt>). We could write <tt>then</tt> at the beginning of a new line, and that is perfectly fine, but it's good for a single script to be consistent one way or the other; using a single, consistent appearance for ordinary constructs makes it easier to notice unusual constructs. In the real world, programmers usually put <tt>; then</tt> at the end of the <tt>if</tt> or <tt>elif</tt> line, so we have followed that convention here.
* A newline is used after <tt>then</tt> and after <tt>else</tt>. These newlines are optional — they need not be (and cannot be) replaced with semicolons — but they promote readability by visually accentuating the structure of the <tt>if</tt> statement.
* Regular commands are separated by newlines, never semicolons. This is a general convention, not specific to <tt>if</tt> statements. Putting each command on its own line makes it easier for someone to "skim" the script and see roughly what it is doing.