简体   繁体   中英

Shell Script with environment variable

I have a C program that has the following code at the end:

    memcpy(buff,"TEST=",4)
    putenv(buff)
    system("/bin/bash")

I put a new environment variable in a new 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. 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.

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.

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 .

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 .

 $ ./cprog "wibble" TEST=wibble $ eval `./cprog "wibble"` $ echo ""TEST\\" is now equal to \\"$TEST\\"" "TEST" is now equal to "wibble" $ 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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