Possible Duplicate:
Echo expanded PS1
Is there any way to ‘evaluate’ PS1, PS2, etc from within a bash script?
Although, I can use alternate means to get all elements of my current PS1, I would really like to be able to reuse its definition instead of using these alternate means.
For example,
=====================================
PS1 element --> Alternate means
=====================================
\u --> $USER
\h --> $HOSTNAME
\w --> $PWD
...
=====================================
I could very well use the ‘alternate means’ column in my script, but I don’t want to. In my PS1, I, for example, use bold blue color via terminal escape sequences which I’d like to be able to simply reuse by evaluating PS1.
One great advantage of open source software is that the source is, well, open 🙂
If you download the code for
bash(I’m looking at version 4.2), there’s ay.tab.cfile which contains thedecode_prompt_string()function:You can try to extract that (along with any needed support routines and build an executable which did the job for you. Although, from a cursory try, those support routines seem to be a lot, so this may be a hard task.
Other than that, you can probably “trick”
bashinto expanding it for you with something like:Now I’ve put that across multiple lines for readability but it was done on one line.
What this does is run an interactive instance of
bash, passing (what hopefully is) an invalid command.Because it’s interactive, it prints the prompt so I grab the first line with the command string on it and remove that command string. What’s left over should be the prompt.
On my system, this is what I get:
However, this has problems with multi-line prompts and will actually give you your regular prompt rather than the current shell one.
If you want to do it properly, it may involve adding a little bit to
bashitself. Here are the steps to add an internal commandevalps1.First, change
support/mkversion.shso that you won’t confuse it with a “real”bash, and so that the FSF can deny all knowledge for warranty purposes 🙂 Simply change one line (I added the-paxbit):Second, change `builtins/Makefile.in to add a new source file. This entails a number of steps.
(a) Add
$(srcdir)/evalps1.defto the end ofDEFSRC.(b) Add
evalps1.oto the end ofOFILES.(c) Add the required dependencies:
Third, add the
builtins/evalps1.deffile itself, this is the code that gets executed when you run theevalps1command:The bulk of that is the GPL licence (since I modified it from
exit.def) with a very simple function at the end to get and decodePS1.Lastly, just build the thing in the top level directory:
The
bashthat appears can be renamed topaxsh, though I doubt it will ever become as prevalent as its ancestor 🙂And running it, you can see it in action:
Now, granted, making code changes to
bashto add an internal command may be considered overkill by some but, if you want an accurate evaluation ofPS1, it’s certainly an option.