[TriLUG] Changing slashes to backslashes in prompt

Aaron Schrab via TriLUG trilug at trilug.org
Fri Apr 19 17:55:09 EDT 2019


At 14:55 -0500 19 Apr 2019, Bick via TriLUG <trilug at trilug.org> wrote:
>I am reading through a Linux book right now and one of the exercises in 
>the chapter about environment variables is to make the prompt look more 
>Windows like.  Specifically, I am supposed to make the prompt display 
>C:\directory.  I first  attempted to use sed to accomplish it like 
>this: PS1='C:$(echo $(pwd) | sed 's:/:\\:g') '.  The result is 
>C:parentDirchildDir.  It does not print slashes.  If I just put the 
>command I am calling directly into the bash prompt, I get the proper 
>output: C:\parentDir\childDir.

The problem is that there are many pieces which will interpret the 
backslash as an escape character.

Here the very first of those happens when you're setting $PS1. The 
single quote after `sed` is ending the quoting for the value, causing 
bash to include just a single backslash, and no quotes, in the value for 
PS1.

Then when bash is evaluating the prompt it looks for backslash-escape 
sequences to be replaced with information, and removes the remaining 
backslash.  So the command that sed ends up seeing is `s:/::g`.

>I thought maybe the problem was that the single slash was being 
>reinterpreted as an escape character when PS1 was being read, so I 
>tried using four slashes (so that two would be present in the PS1 
>string).  Again typing this at the command prompt worked (output was 
>C:\\parentDir\\childDir), but it didn't work as part of assigning it to 
>PS1.

This would behave somewhat similarly as above. The 4 backslashes get 
converted to 2 before being put into $PS1, the prompt evaluation 
converts that to a single backslash, and that gets removed by the 
subshell that's handling the `$()` construct. So sed still gets the same 
command as in the previous case.

Things *do* tend to get quite complicated when there are multiple levels 
of quoting needed.

I figured most of this out by playing around with that while doing `echo 
$PS1` to show what value was actually getting into that, and having `set 
-x` in effect to show the commands that get executed.

BTW, the `echo $()` is unnecessary there. You can do `$(pwd | sed)`. You 
may also want to look into using `${PWD/...}` (dots left as an excercise 
for the reader).
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 549 bytes
Desc: not available
URL: <http://www.trilug.org/pipermail/trilug/attachments/20190419/6f4d68e6/attachment.pgp>


More information about the TriLUG mailing list