0

I would like to see the output of the escaped special characters used in setting up $PS1. For example, placing \u in PS1 will output the username of the current user.

So in essence:

omar @ ~ > echo -e '\u'

Expect:

omar

Actual output:

\u
Omar
  • 37,391
  • 42
  • 132
  • 207
  • 1
    One approach for the truly geeky among us: http://stackoverflow.com/questions/3451993/echo-expanded-ps1/14231995#14231995 - in any case, this looks like a duplicate. – paxdiablo Feb 01 '13 at 03:11

2 Answers2

1

You can do it with parameter expansion with the @P operator like this:

prompt="\u"; echo ${prompt@P}

As of Bash 4.4, you can use the @P operator in Parameter expansion:

${parameter@operator}
The expansion is either a transformation of the value of parameter or information about parameter itself, depending on the value of operator. Each operator is a single letter:

@P The expansion is a string that is the result of expanding the value of parameter as if it were a prompt

Here's some of the common special characters available to the PS1 command:

The following lists the special characters that can appear in the prompt variables PS0, PS1, PS2, and PS4

\a A bell character
\d The date, in "Weekday Month Date" format (e.g., "Tue May 26")
\e An escape character
\H The hostname
\u The username of the current user
\w The current working directory

Further Reading:

Community
  • 1
  • 1
KyleMit
  • 45,382
  • 53
  • 367
  • 544
  • Interesting. I had not made use of the `${foo@P}` prompt expansion before (never had the need). Thankfully, Bash 5 doesn't seem to have changed or added to parameter expansions. [Bash-5.0 release available](https://lists.gnu.org/archive/html/bug-bash/2019-01/msg00063.html) – David C. Rankin Jan 14 '19 at 01:33
0

Here's one approach that can be used to show the value of an escaped character.

The functions defined below will change your current PS1 to the given string. You can see the output right after entering the command.

  1. Store your current PS1 in a variable

    > save=$PS1

  2. Create a reset function

    > function reset { PS1=$save; }

  3. Create the print function

    > function omar { PS1="\\$1 "; }

  4. Use it as follows

    > omar u: Your command prompt will be your username

    omar >

    > omar @: Your command prompt will be the current time in 12-hour am/pm format

    11:19 PM >

    > omar h: Your command prompt will be the hostname up to the first `.'

    omar-Laptop >

    etc...

  5. You can reset your PS1 by either calling reset or restarting the terminal

Omar
  • 37,391
  • 42
  • 132
  • 207