Linux getenv () could not get $ PS1 or $ PS2

My home world has to write a shell. and I have to use $PS2 .

but when I write this code:

 char *ENV_ps2; ENV_ps2 = getenv("PS2"); 

I just found ENV_ps2 , pointed to (null) .

How can I get $PS2 in my program?

+7
source share
3 answers

Shell variables PS1 and PS2 not exported and therefore not available to 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= 
+6
source

In bash, $PS1 and $PS2 are shell variables, not environment variables (at least usually). They are set to default values ​​within bash independently or explicitly set by the user either interactively or when a script is run, for example .profile or .bashrc .

They cannot be accessed through getenv() , and they are not inherited by forked subprocesses. They are controlled internally by the shell of its own mechanism for shell variables.

If you are writing your own shell, it might make sense to do something like this.

You can see the source code of bash. It's big and complex, but finding PS1 and PS2 can be instructive. (You do not need to use the exact same bash mechanism, most likely you will need something simpler.)

(You can enter export PS1 to turn $PS1 into an environment variable, but that doesn't make much sense for this.)

+2
source

These env vars are not exported.

If you need a non-portable approach, you can simply define and export an arbitrary environment variable and set PS1 / PS2 to this value in your .bashrc / .bash_profile.

eg:

 # bashrc MY_PS1="..........." export $MY_PS1 ... ... ... PS1=$MY_PS1 
+1
source

All Articles