112
回編集
M (→サブシェル) |
M (→サブシェル) |
||
{{Transwiki:Bash Shell Scripting/tip|変数の値を一時的に変更する関数が必要な場合、-- 呼び出し中は修正した値を使用し呼び出し後に元の値に戻したい場合 -- その関数呼び出しを丸括弧でくくることができます。これをサブシェルといいます。サブシェルは修正を ''隔離'' しそのまわりの実行環境へ影響を波及させません。(可能な場合、この方法で記述した関数は問題が起きにくいです。また <tt>local</tt> キーワードも助けてくれます。)}}
これは関数の定義も同じ点があります。通常の変数と同じでサブシェルの中で定義されたシェル関数はそのサブシェルの外からは見えません。
サブシェルはまた実行環境の他の要素の変更も区別します。特に <tt>cd</tt> ("change directory")コマンドが影響するのはサブシェルの中だけです。スクリプトの例をあげます。
<source lang="bash">#!/bin/bash
</source>
{{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.)}}
|
回編集