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`
.)