tmp.txt
エクスポートする変数を含むファイルがあります。たとえば、次のようになります。
a=123
b="hello world"
c="one more variable"
export
後で子プロセスで使用できるようにコマンドを使用してこれらすべての変数をエクスポートするにはどうすればよいですか?
ベストアンサー1
set -a
. ./tmp.txt
set +a
set -a
これから定義された変数を自動的にエクスポートするようにします。 Bourneに似たすべてのシェルで使用できます。.
はコマンドの標準とBourne名なsource
ので、移植性のために好みます(時々少し異なる動作を含む)を含むsource
ほとんどcsh
の現代のBourne様シェルで利用可能です。bash
POSIXシェルでは、set -o allexport
より説明的な代替(set +o allexport
unset)を使用して作成することもできます。
以下を使用して関数にすることができます。
export_from() {
# local is not a standard command but is pretty common. It's needed here
# for this code to be re-entrant (for the case where sourced files to
# call export_from). We still use _export_from_ prefix to namespace
# those variables to reduce the risk of those variables being some of
# those exported by the sourced file.
local _export_from_ret _export_from_restore _export_from_file
_export_from_ret=0
# record current state of the allexport option. Some shells (ksh93/zsh)
# have support for local scope for options, but there's no standard
# equivalent.
case $- in
(*a*) _export_from_restore=;;
(*) _export_from_restore='set +a';;
esac
for _export_from_file do
# using the command prefix removes the "special" attribute of the "."
# command so that it doesn't exit the shell when failing.
command . "$_export_from_file" || _export_from_ret="$?"
done
eval "$_export_from_restore"
return "$_export_from_ret"
}
¹in bash
、これはすべての問題を引き起こすことに注意してください。機能whileステートメントallexport
は環境にエクスポートされます(実行中でも、BASH_FUNC_myfunction%%
その環境で実行されているすべてのシェルがその後に環境変数を取得します)。bash
sh