如何通过shell脚本导出变量?

时间:2012-06-18 02:30:13

标签: shell ubuntu

a.sh

#! /bin/sh
export x=/usr/local

我们可以在命令行中执行source ./a。但我需要通过shell脚本进行导出。

b.sh

#! /bin/sh
. ~/a.sh

没有错误......但命令行中的$x将不显示任何内容。所以它没有出口。

知道如何让它发挥作用吗?


a.sh

#! /bin/sh
export x=/usr/local
-----------
admin@client: ./a.sh
admin@client: echo $x

admin@client:  <insert ....>

6 个答案:

答案 0 :(得分:58)

您可以将导出语句放在shell脚本中,然后使用'source'命令在当前进程中执行它

source a.sh

我希望这会有所帮助。

答案 1 :(得分:20)

您不能通过shell脚本进行导出,因为shell脚本在子shell进程中运行,并且只有子shell的子进程才会继承导出。

使用source的原因是让当前shell执行命令

将导出命令放在诸如.bashrc之类的文件中是非常常见的,bash将在启动时获取该文件(或其他shell的类似文件)

另一个想法是你可以创建一个shell脚本,它在输出时生成一个导出命令:

shell$ cat > script.sh
#!/bin/sh
echo export foo=bar
^D
chmod u+x script.sh

然后让当前shell执行该输出

shell$ `./script.sh`

shell$ echo $foo
bar

shell$ /bin/sh
$ echo $foo
bar

(注意上面脚本的调用被反引号包围,导致shell 执行脚本的输出)

答案 2 :(得分:1)

将变量导出到环境中只会使该变量对子进程可见。孩子无法修改其父母的环境。

答案 3 :(得分:1)

你可以做的另一种方法(窃取/阐述上述想法)是将脚本放在〜/ bin中并确保〜/ bin在你的PATH中。然后,您可以全局访问您的变量。这只是我用来编译Go源代码的一个例子,它需要GOPATH变量指向当前目录(假设你在编译源代码的目录中):

来自〜/ bin / GOPATH:

#!/bin/bash

echo declare -x GOPATH=$(pwd) 

然后你就做了:

#> $(GOPATH)

因此,您现在也可以在其他脚本中使用$(GOPATH),例如自定义构建脚本,它可以自动调用此变量并通过$(pwd)动态声明它。

答案 4 :(得分:1)

使用上面的答案在这里回答我自己的问题:如果我要导出多个相关变量,并且每次导出使用相同的值,则可以执行以下操作:

#!/bin/bash
export TEST_EXPORT=$1
export TEST_EXPORT_2=$1_2
export TEST_EXPORT_TWICE=$1_$1

并另存为〜/ Desktop / TEST_EXPORTING

最后是$chmod +x ~/Desktop/TEST_EXPORTING

-

然后,使用source ~/Desktop/TEST_EXPORTING bob

运行它

然后使用export | grep bob进行检查应显示您的期望。

答案 5 :(得分:0)

script1.sh

shell_ppid=$PPID
shell_epoch=$(grep se.exec_start "/proc/${shell_ppid}/sched" | sed 's/[[:space:]]//g' | cut -f2 -d: | cut -f1 -d.)
now_epoch=$(($(date +%s%N)/1000000))
shell_start=$(( (now_epoch - shell_epoch)/1000 ))
env_md5=$(md5sum <<<"${shell_ppid}-${shell_start}"| sed 's/[[:space:]]//g' | cut -f1 -d-)
tmp_dir="/tmp/ToD-env-${env_md5}"
mkdir -p "${tmp_dir}"
ENV_PROPS="${tmp_dir}/.env"
echo "FOO=BAR" > "${ENV_PROPS}"

script2.sh

shell_ppid=$PPID
shell_epoch=$(grep se.exec_start "/proc/${shell_ppid}/sched" | sed 's/[[:space:]]//g' | cut -f2 -d: | cut -f1 -d.)
now_epoch=$(($(date +%s%N)/1000000))
shell_start=$(( (now_epoch - shell_epoch)/1000 ))
env_md5=$(md5sum <<<"${shell_ppid}-${shell_start}"| sed 's/[[:space:]]//g' | cut -f1 -d-)
tmp_dir="/tmp/ToD-env-${env_md5}"
mkdir -p "${tmp_dir}"
ENV_PROPS="${tmp_dir}/.env"
source "${ENV_PROPS}"
echo $FOO
./script1.sh
./script2.sh
BAR

对于在同一父shell中运行的脚本,它仍然存在,并且可以防止冲突。