'Linux getenv() could not get $PS1 or $PS2
My home world is to write a shell. and I must use $PS2
.
but when I write a code like this:
char *ENV_ps2;
ENV_ps2 = getenv("PS2");
I just found ENV_ps2
was point to (null)
.
how could I get the $PS2
in my program ?
Solution 1:[1]
The PS1
and PS2
shell variables are not exported and are therefore inaccessible from child processes. You can test this with a simple script:
$ cat /tmp/pstest.sh
#!/bin/sh
echo PS1=$PS1
echo PS2=$PS2
$ /tmp/pstest.sh
PS1=
PS2=
Solution 2:[2]
In bash, $PS1
and $PS2
are shell variables, not environment variables (at least normally). They're set to default values within bash itself, or set explicitly by the user either interactively or in a startup script such as .profile
or .bashrc
.
They can't be accessed via getenv()
, and they aren't inherited by forked subprocesses. They're managed internally by the shell's own mechanism for shell variables.
If you're writing your own shell, it probably makes sense to do something similar.
You might take a look at the bash source code. It's large and complex, but searching for PS1
and PS2
might be instructive. (You don't have to use exactly the same mechanism bash uses; it's likely you'll want something simpler.)
(You can type export PS1
to turn $PS1
into an environment variable, but it doesn't make much sense to do so.)
Solution 3:[3]
Those env vars are not exported.
If you want a non-portable approach, you could just define and export an arbitrary environment variable, and set PS1/PS2 to that value in your .bashrc/.bash_profile.
eg:
# bashrc
MY_PS1="..........."
export $MY_PS1
...
...
...
PS1=$MY_PS1
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Keith Thompson |
Solution 3 | Cloud |