「Transwiki:Bash Shell Scripting」の版間の差分
削除された内容 追加された内容
M →反復・ループ |
M →シェル関数 |
||
635 行
==シェル関数==
''シェル関数''は特別な種類の変数で、スクリプト内に書かれたスクリプトと言えます。シェル関数により、一連のコマンドを一つの名前のコマンドにまとめられます。これは、ある一連のコマンドをスクリプト内の色々な場所から(複数回)実行する場合に特に便利です。シェル関数は1つのコマンドだけでも構成できます。これは、元にするコマンドが特別に複雑な場合や、元のコマンドの意味や意図が読者にすぐにはわからりにくい場合に便利です。 (つまり、シェル関数は2つの目的があります。入力を節約できます。また名前の付いたコマンドを作成して、直感的にコードを読みやすくすることができます。)次のスクリプトを見てください
<source lang="bash">#!/bin/bash
653 行
</source>
上のスクリプトは<tt>get_password</tt>という名前のシェル関数を作成しています。これは、ユーザーにパスワードの入力を求め、その結果を指定した変数に保管します。<tt>get_password PASSWORD</tt>を実行するとパスワードは<tt>$PASSWORD</tt>に保存されます。<tt>get_password</tt>の呼び出しが成功した場合(これはその終了値によって決まる)、取得したパスワードを標準出力に出力します(これは現実的な仕様ではありません。ここでは<tt>get_password</tt>の動作を説明することだけが目的です)。
The function <tt>get_password</tt> doesn't do anything that couldn't be done without a shell function, but the result is much more readable. The function invokes the built-in command <tt>read</tt> (which reads a line of user input and saves it in one or more variables) with several options that most Bash programmers will not be familiar with. (The <tt>-r</tt> option disables a special meaning for the backslash character; the <tt>-p</tt> option causes a specified prompt, in this case <tt>Password:</tt>, to be displayed at the head of the line; and the <tt>-s</tt> option prevents the password from being displayed as the user types it in. Since the <tt>-s</tt> option also prevents the user's newline from being displayed, the <tt>echo</tt> command supplies a newline.) Additionally, the function uses the conditional expression <tt>-t 0</tt> to make sure that the script's input is coming from a terminal (a console), and not from a file or from another program that wouldn't know that a password is being requested. (This last feature is debatable; depending on the general functionality of the script, it may be better to accept a password from standard input regardless of its source, under the assumption that the source was designed with the script in mind.) The overall point is that giving sequence of commands a name — <tt>get_password</tt> — makes it much easier for a programmer to know what it does.
|