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

这个问题很简单,我想在bash脚本中评估PS1的当前值。

是否有任何软件/函数可以帮助我实现这一目标?

时间:


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:


show-prompt


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

${parameter@operator}

参数转换,扩展是参数值的变换或参数本身的信息,取决于运算符的值。
每个运算符都是一个字母:


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.



参数为@*,则操作将依次应用于每个位置参数,而展开是结果列表,如果参数是使用@或*下标的数组变量,则操作依次应用于数组的每个成员,并且扩展是结果列表。

编辑/etc/bashrc文件

您可以将此作为示例并检查输出


 # 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] $"


fi



...