Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 359
thlgood Avatar asked May 08 '12 15:05

thlgood


3 Answers

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=
like image 55
trojanfoe Avatar answered Sep 30 '22 11:09

trojanfoe


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

like image 27
Keith Thompson Avatar answered Sep 30 '22 10:09

Keith Thompson


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
like image 31
Cloud Avatar answered Sep 30 '22 10:09

Cloud