[英]Shell Script with environment variable
I have a C program that has the following code at the end: 我有一个C程序,结尾处有以下代码:
memcpy(buff,"TEST=",4)
putenv(buff)
system("/bin/bash")
I put a new environment variable in a new shell. 我在新的shell中放入了新的环境变量。 I want to then echo test into a text file which i can easily do.
然后,我想将测试回显到我可以轻松完成的文本文件中。 I then want to exit the shell and run it again so running this would look as follows
然后,我想退出外壳并再次运行它,因此运行如下
./cprog "some arg"
echo $TEST > test.txt
exit
./cprog "some arg"
echo $TEST > test.txt
exit
I have to keep exiting so I can change the TEST variable. 我必须继续退出,以便可以更改TEST变量。 How could I make this work in a shell script so i could just keep looping and running the c program so I could change the argument but never exiting the shell script itself.
我如何才能在shell脚本中完成此工作,以便我可以继续循环并运行c程序,以便可以更改参数,而从不退出shell脚本本身。
Environment variables are not an appropriate way of passing information from a process to the user or an invoking process. 环境变量不是将信息从流程传递给用户或调用流程的适当方法。 You should be writing this information to stdout (with any other info to stderr) and redirecting it appropriately.
您应该将此信息写入stdout(将其他任何信息写入stderr)并适当地重定向。
If you insist on this solution, though, you can use 如果您坚持使用此解决方案,则可以使用
for p in "one arg" "another arg" "more"
do
echo 'printf "%s\n" "$TEST" >> test.txt' | ./cprog "$p"
done
This will input the command to write the variable to the file to your program, and then exit the shell (because input ends). 这将输入命令以将变量写入文件到程序中,然后退出外壳程序(因为输入结束)。
At the end, you'll have all the values of $TEST
concatenated in the file test.txt
. 最后,您将在文件
test.txt
连接所有$TEST
的值。
It isn't possible for your program to change the environment of the parent process, which is what you seem to be trying to do. 您的程序不可能更改父进程的环境,这似乎是您试图做的。
What you can do instead, however, is to have your program simply print the desired output, and call it using eval
. 但是,您可以做的是让您的程序仅打印所需的输出,然后使用
eval
调用。
$ ./cprog "wibble" TEST=wibble $ eval `./cprog "wibble"` $ echo ""TEST\\" is now equal to \\"$TEST\\"" "TEST" is now equal to "wibble" $
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.