[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Bash and the PS1 environment variable [was: grep: show matching line from pattern file]



On 6/2/22 19:25, Greg Wooledge wrote:
On Thu, Jun 02, 2022 at 06:01:11PM -0700, David Christensen wrote:
This is my PS1.  '\u' does not work on all of Debian, FreeBSD, Cygwin, and
macOS, so the expansion of ${USER} is inserted between two string literals
when .profile runs and sets PS1:

2022-06-02 17:39:09 dpchrist@laalaa ~
$ grep PS1 .profile
export PS1='\n\D{%Y-%m-%d %H:%M:%S} '${USER}'@\h \w\n\$ '

Variable expansions *are* performed when PS1 is evaluated.  So, you
could simply do:

PS1='stuff $USER more stuff'

That will delay the expansion of USER (which by the way is a BSD-ism)
until the prompt is drawn.  The way you've written it, $USER is
expanded at the time PS1 is assigned.  Which is not wrong, so long as
the value of USER cannot change in the middle of a shell session...
but it's not how most of the experienced people would do it, I think.

I'm rather curious how you managed to find a system + bash version
where \u doesn't work.  That sounds like something you'd want to report
to the bug-bash mailing list... or, possibly, a user error.  \u should
work on any Unix-like system.


I found the reason for not using '\u' in Bash PS1 -- the 'toor' user on FreeBSD:

2022-06-02 21:30:08 toor@f3 ~
# freebsd-version ; uname -a ; bash --version
12.3-RELEASE-p5
FreeBSD f3.tracy.holgerdanske.com 12.3-RELEASE-p5 FreeBSD 12.3-RELEASE-p5 GENERIC amd64
GNU bash, version 5.1.16(0)-release (amd64-portbld-freebsd12.3)
Copyright (C) 2020 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

2022-06-02 21:30:16 toor@f3 ~
# egrep '^(root|toor)' /etc/passwd
root:*:0:0:Charlie &:/root:/bin/csh
toor:*:0:0:Bourne-again Superuser:/root:/usr/local/bin/bash

2022-06-02 21:30:28 toor@f3 ~
# whoami
root

2022-06-02 21:30:30 toor@f3 ~
# echo $USER
toor

2022-06-02 21:30:34 toor@f3 ~
# PS1='\n\D{%Y-%m-%d %H:%M:%S} \u@\h \w\n\$ '

2022-06-02 21:30:41 root@f3 ~
#


Your suggestion produces the desired prompt:

2022-06-02 21:30:41 root@f3 ~
# PS1='\n\D{%Y-%m-%d %H:%M:%S} $USER@\h \w\n\$ '

2022-06-02 21:31:29 toor@f3 ~
#


But, I think I will keep the braces:

2022-06-02 21:55:38 toor@f3 ~
# vi .profile

    export PS1='\n\D{%Y-%m-%d %H:%M:%S} ${USER}@\h \w\n\$ '

2022-06-02 21:56:04 toor@f3 ~
# . .profile

2022-06-02 21:56:06 toor@f3 ~
# echo $PS1
\n\D{%Y-%m-%d %H:%M:%S} ${USER}@\h \w\n\$

2022-06-02 21:56:10 toor@f3 ~
#


(It works on all of my other platforms.)


Thank you,

David


Reply to: