bash - 如何打印当前的bash提示?




show-prompt() {

 eval 'echo -en"'$PS1'"' | sed -e 's#[##g' -e 's#]##g'


# To show it in a function registered with `complete -F` on

# a single tab, and keep the user's input:


echo -n"${COMP_WORDS[@]}"


echo $PS1 | 

sed -e s/'d'/"$(date +'%a %b %_d')"/g | 

sed -e s/'t'/"$(date +'%T')"/g | 

sed -e s/'@'/"$(date +'%r')"/g | 

sed -e s/'T'/"$(date +'%r'| awk {'print $1'})"/g | 

sed -e s/'e'//g | sed -e s/'h'/"$HOSTNAME"/g | 

sed -e s/'h'/"$HOSTNAME"/g | 

sed -e s/'H'/"$HOSTNAME"/g | 

sed -e s/'u'/"$USER"/g | 

sed -e s@'W'@"$(pwd)"@g | 

sed -e s/'w'/"$(pwd | sed -e s@$HOME@'~'@g )"/g | 

sed -e s/""//g | 

sed -e s/"["//g | 

sed -e s/"]"/*/g | 

cut -d'*' -f2 | 

cut -d';' -f2 | 

sed s/ //g | 

sed -e s/[a-z]$/"$(["$USER" !="root" ] && echo $ || echo #)"/g

Bash 4.4 解决方案,使用参数转换作为提示字符串: echo"${PS1@P}"

[adamhotep@tabasco ~/Downloads]$ echo"the prompt is '${PS1@P}'"

the prompt is '[adamhotep@tabasco ~/Downloads]$'

[adamhotep@tabasco ~/Downloads]$ TEST_STRING='u is dining at t using s V'

[adamhotep@tabasco ~/Downloads]$ echo"${TEST_STRING}"

u is dining at t using s V

[adamhotep@tabasco ~/Downloads]$ echo"${TEST_STRING@P}"

adamhotep is dining at 21:45:10 using bash 5.0.3

[adamhotep@tabasco ~/Downloads]$ 

BASH参考手册页上shell Parameter Expansion



Q The expansion is a string that is the value of parameter quoted in a

 format that can be reused as input.

E The expansion is a string that is the value of parameter with backslash

 escape sequences expanded as with the $'...' quoting mechanism.

P The expansion is a string that is the result of expanding the value of

 parameter as if it were a prompt string (see PROMPTING below).

A The expansion is a string in the form of an assignment statement or

 declare command that, if evaluated, will recreate parameter with its

 attributes and value.

a The expansion is a string consisting of flag values representing

 parameter's attributes.




 # If id command returns zero, you've root access.

if [ $(id -u) -eq 0 ];

then # you are root, set red colour prompt

 PS1="[$(tput setaf 1)]u@h:w #[$(tput sgr0)]"

else # normal

 PS1="[u@h:w] $"