Chanakya.sun
Chanakya.sun

Reputation: 587

setenv() to update PATH environment variable

i want to write a C program to append a string to PATH Environment variable. something like "export PATH=$PATH:$HOME/mylib"

i have C code like this

setenv("PATH", "$PATH:$HOME/mylib",1); //which does not work.

other work arround i thought was get PATH and HOME using getenv() and create a memory in heap then append them using strcat().

I might have to update PATH many times in my code: so this is a tiresome process.

is there any alternative?

Thanks

Upvotes: 0

Views: 6307

Answers (3)

Keith Thompson
Keith Thompson

Reputation: 263577

The $FOO syntax, which expands to the value of the environment variable with the name FOO, is a feature of the shell; it's not directly available in C.

Your system may provide the wordexp() function, which gives you similar functionality in C.

But since you're just expanding two environment variables with fixed names ("HOME" and "PATH"), it makes more sense to use the portable getenv() function and a little string processing. (You might consider using sprintf or snprintf rather than strcat.)

NOTE: If you're only using the updated $PATH internally in your program, you can stop reading here.

Hopefully you're not expecting any changes to $PATH to be available on the command line after your program finishes running. Your running C program is most likely a child process of your interactive shell. Environment variables are inherited by child processes; they don't propagate back to parent proceses.

If that's what you're trying to do, you can have your program print the new PATH value to stdout, and then have the shell evaluate it:

PATH=`your-program`

Or it can print the command(s) to set one or more environment variables:

eval `your-program`

(In bash, you can use $(your-program) as well as `your-program`.)

Upvotes: 2

Roman Dmitrienko
Roman Dmitrienko

Reputation: 4235

There is no other option immediately available. You can write a separate function to handle this, if you need to do it several times.

Upvotes: 1

bmargulies
bmargulies

Reputation: 100151

No there is no alternative. You have to build the literal string and pass it to setenv.

Upvotes: 1

Related Questions