[英]Save an environment variable without using /bin/bash
I have a program that creates a environment variable called $EGG
with this code 我有一个使用此代码创建名为
$EGG
的环境变量的程序
memcpy(buff,"EGG=",4);
putenv(buff);
system("/bin/bash");
And the value of buff
is used to create an environment variable, and I use it through $EGG
variable, but for use it I see that I must use the call system("/bin/bash");
buff
的值用于创建环境变量,我通过$EGG
变量使用它,但是要使用它,我看到我必须使用调用system("/bin/bash");
. 。 Otherwise, if I don't use /bin/bash call I don't find my
$EGG
variable. 否则,如果我不使用/ bin / bash调用,则找不到
$EGG
变量。
Is there a way to save my environment variable without calling /bin/bash
? 有没有一种方法可以在不调用
/bin/bash
情况下保存我的环境变量?
Short answer: You cannot modify an existing environment the way you try. 简短的答案:您不能以尝试的方式修改现有环境。
Background: The program you use to create the environment variable EGG
in gets its own environment on start-up (typically as copy of the environment of the process that starts the program). 背景:用于创建环境变量
EGG
的程序在启动时会得到自己的环境(通常是启动程序的进程环境的副本)。 Inside the program's very own environment EGG
is created. 在程序自己的环境中创建了
EGG
。
When a program ends its environment is also gone and with it would had been created in there. 当程序结束时,它的环境也消失了,并且已经在其中创建了环境。
To modify an environment programmatically do not write a (C) program but use a script. 要以编程方式修改环境,请不要编写(C)程序,而要使用脚本。
Using bash this could look like this: 使用bash可能看起来像这样:
#!/bin/bash
export EGG=4
save this as for example set_egg_to_4.sh
and adjust the files mode do be able to execute the it: 将其保存为例如
set_egg_to_4.sh
并调整文件模式可以执行它:
$ chmod +x set_egg_to_4.sh
Then run the script: 然后运行脚本:
$ ./set_egg_to_4.sh
and test for EGG
, by doing 并通过做
EGG
测试
$ echo $EGG
4
To "permanently" set an environment variable, add it to your .bash_profile
file. 要“永久”设置环境变量,请将其添加到您的
.bash_profile
文件中。
export EGG=4
This file is sourced each time you start a login session, so that EGG
is added to your environment each time. 每次启动登录会话时都会获取此文件,因此每次都会将
EGG
添加到您的环境中。 Any that inherit (directly or indirectly) from this shell will also have EGG
in its environment. 任何从该shell继承(直接或间接)的对象在其环境中也将具有
EGG
。
There may be other files on your system that are sourced immediately on startup, so that a variable set in such a file is available to all processes (regardless of the user). 系统上可能有其他文件,这些文件是在启动时立即获取的,因此,在此文件中设置的变量可用于所有进程(无论用户如何)。 (One I'm think of is
/etc/environment
.) (我想到的是
/etc/environment
。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.