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

削除された内容 追加された内容
Fu7mu4 (トーク | 投稿記録)
Fu7mu4 (トーク | 投稿記録)
693 行
{{Transwiki:Bash Shell Scripting/tip|変数の値を一時的に変更する関数が必要な場合、-- 呼び出し中は修正した値を使用し呼び出し後に元の値に戻したい場合 -- その関数呼び出しを丸括弧でくくることができます。これをサブシェルといいます。サブシェルは修正を ''隔離'' しそのまわりの実行環境へ影響を波及させません。(可能な場合、この方法で記述した関数は問題が起きにくいです。また <tt>local</tt> キーワードも助けてくれます。)}}
 
これは関数の定義も同じ点があります。通常の変数と同じでサブシェルの中で定義されたシェル関数はそのサブシェルの外からは見えません。
The same is true of function definitions; just like a regular variable, a function defined within a subshell is not visible outside the subshell.
 
サブシェルはまた実行環境の他の要素の変更も区別します。特に <tt>cd</tt> ("change directory")コマンドが影響するのはサブシェルの中だけです。スクリプトの例をあげます。
A subshell also delimits changes to other aspects of the execution environment; in particular, the <tt>cd</tt> ("change directory") command only affects the subshell. So, for example, this script:
 
<source lang="bash">#!/bin/bash
712 行
</source>
 
prints this出力内容: <pre>/&#xA;/&#xA;/home&#xA;/</pre>
 
{{Transwiki:Bash Shell Scripting/tip|If your script needs to change the working directory before running a given command, it's a good idea to use a subshell if possible. Otherwise it can become hard to keep track of the working directory when reading a script. (Alternatively, the <tt>pushd</tt> and <tt>popd</tt> built-in commands can be used to similar effect.)}}