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

削除された内容 追加された内容
Fu7mu4 (トーク | 投稿記録)
Fu7mu4 (トーク | 投稿記録)
778 行
上のスクリプトは <tt>bar</tt>と出力します。 一行のスクリプトの内部で <tt>$foo</tt> 変数を変更していますが、その変更は呼び出し側のプロセスには影響しません。(しかしそのスクリプトによって呼び出されたスクリプトには影響するでしょう。)
 
特定の環境変数を1つのコマンドだけに影響させたい場合、同じ行のコマンドの前に変数割り当て(複数の変数割り当ても可能)の構文を使用して、<source lang="bash" enclose="none">var=value command</source> といった構文を使用できます。(変数割り当ての構文を使用しているにもかかわらず、通常のBash変数割り当てとは大きく異なります。これらは変数は自動的に環境にエクスポートされますが、1つのコマンドに対してのみ影響します。
If a given environment variable is desired for just one command, the syntax <source lang="bash" enclose="none">var=value command</source> may be used, with the syntax of a variable assignment (or multiple variable assignments) preceding a command on the same line. (Note that, despite using the syntax of a variable assignment, this is very different from a normal Bash variable assignment, in that the variable is automatically exported into the environment, and in that it only exists for the one command. If you want avoid the confusion of similar syntax doing dissimilar things, you can use the common Unix utility <tt>env</tt> for the same effect. That utility also makes it possible to ''remove'' an environment variable for one command — or even to remove ''all'' environment variables for one command.) If <tt>$var</tt> already exists, and it's desired to include its actual value in the environment for just one command, that can be written as <source lang="bash" enclose="none">var="$var" command</source>.
変数割り当てと似た文法でこれとは全く異なった効果があります。これを混乱を避けたいのなら、同じ効果を得るために一般的なUnixユーティリティ<tt> env </tt>を使いましょう。このユーティリティは、1つのコマンドの環境変数を ''削除''できます。または1回のコマンドで ''全て''の環境変数を削除できます。)もし<tt> $var </tt>がすでに存在し、かつ実際の値を1つのコマンドだけの実行環境にだけ影響させたい場合、<source lang = "bash" enclose = "none"> var="$var" command </source>として実行できます。
 
An aside: sometimes it's useful to put variable definitions — or function definitions — in one Bash script (say, <tt>header.sh</tt>) that can be called by another Bash script (say, <tt>main.sh</tt>). We can see that simply invoking that other Bash script, as <tt>./header.sh</tt> or as <tt>bash ./header.sh</tt>, will not work: the variable definitions in <tt>header.sh</tt> would not be seen by <tt>main.sh</tt>, not even if we "exported" those definitions. (This is a common point of confusion: <tt>export</tt> exports variables into the environment so that other processes can see them, but they're still only seen by ''child'' processes, not by ''parents''.) However, we can use the Bash built-in command <tt>.</tt> ("dot") or <tt>source</tt>, which runs an external file almost as though it were a shell function. If <tt>header.sh</tt> looks like this: