GNU Bash and Environment Variables in the PS1

By | January 27, 2012

Update – Sorry, while the patch below works, it’s NOT needed to get that functionality!! GNU bash can do that without modifications. I don’t know why I missed that before:-( Simply add a ${VAR} into the single quotes when you define the PS1!

$ PS1='\u@${FOO}\$ '
marcow@YY$ FOO=XX
marcow@XX$

Sorry for the confusion

— Marco

OK, long time nothing new here:-( I did a lot of stuff but nothing really interesting for the outside. But today I had a little problem which might also be useful for others – Adding the value of a shell variable into the GNU Bash prompt.

I followed the \D{<format>} example and added an \E{var_name} to the bash 4.2.20 sources. It seems to work as expected and even honours changes to the variable;-)


root@foo:~$ echo $PS1
\u@\E{MW_HOST}:\w$
root@foo:~$ MW_HOST=x
root@x:~$ MW_HOST=mwbuild01z1
root@mwbuild01z1:~$

The little patch to the parse.y source is below. For interested people without bison/yacc, the same patch could be added to the included y.tab.c file.


--- bash-4.2.20.orig/parse.y    2012-01-28 00:42:44.010257843 -0600
+++ bash-4.2.20/parse.y 2012-01-27 22:00:55.192082732 -0600
@@ -5199,6 +5199,37 @@
temp = savestring (timebuf);
goto add_string;

+/* MARCO */
+            case ‘E’:           /* Environment Variable */
+              {
+                char *var_name;
+
+                if (string[1] != ‘{‘)           /* } */
+                  goto not_escape;
+
+               string += 2;                    /* skip { */
+               var_name = xmalloc (strlen (string) + 3);
+               for (t = var_name; *string && *string != ‘}’; )
+                 *t++ = *string++;
+
+               *t = ‘\0’;
+               c = *string;    /* tested at add_string */
+
+                t = get_string_value(var_name);
+                if (t == (char *)NULL)
+                  t = “”;
+
+                if (promptvars || posixly_correct)
+                  /* Make sure that expand_prompt_string is called with a
+                     second argument of Q_DOUBLE_QUOTES if we use this
+                     function here. */
+                  temp = sh_backslash_quote_for_double_quotes(t);
+                else
+                  temp = savestring(t);
+
+                goto add_string;
+              }
+
case ‘n’:
temp = (char *)xmalloc (3);
temp[0] = no_line_editing ? ‘\n’ : ‘\r’;

Maybe that helps somebody else. The patch is very small but it might still create problems with the formatting, so here is a download version bash-4.2.20.patch.

As always, have fun;-)

— Marco

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.