简体   繁体   English

在bash中分叉子外壳时如何加载环境变量?

[英]how to load environment variables when fork a sub shell in bash?

The next bash script was called in crontab. 下一个bash脚本在crontab中被调用。

I defined some environment variables for python in /etc/profile.d/python.sh. 我在/etc/profile.d/python.sh中为python定义了一些环境变量。

$JOBCMD was some python script which will runing for long time, so I want to the script be called with fork. $ JOBCMD是一些会长期运行的python脚本,因此我想用fork调用该脚本。

#!/bin/sh

. /etc/profile.d/python.sh

JOBCMD=`/path/to/a_long_time_shell.py`

if [ -z "$variable" ]; then
    (
        . /etc/profile.d/python.sh
        $JOBCMD &
    )
fi

exit 0

The result is $JOBCMD can't get environment variables in /etc/profile.d/python.sh? 结果是$ JOBCMD无法在/etc/profile.d/python.sh中获取环境变量? How can I do to fix it? 我该如何解决?

The easiest way I can see of doing this is to export the variables in python.sh : 我看到的最简单的方法是在python.sh导出变量:

export a=123
export b=234

instead of 代替

a=123
b=234

which I guess you're doing. 我猜你在做什么。

Or if you know which variables you want, you could export them before you call the script: 或者,如果知道所需的变量,则可以在调用脚本之前将其导出:

...
. /etc/profile.d/python.sh
export a
export b
$JOBCMD &
...
export JOBCMD=`/path/to/a_long_time_shell.py`

Should make it available to all newly created process. 应该使它可用于所有新创建的过程。 Or, even better. 或者,甚至更好。 You could use psutils to find the process by name and do something with it that way. 您可以使用psutils按名称查找进程,并以此方式进行处理。 Passing things into the environment is a weird way to do IPC. 将事物传递到环境中是进行IPC的一种怪异方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM