bash - BASH 提示符中的正确返回值
问题描述
这是.bashrc
在 Ubuntu 19.10 机器上设置提示的文件的一部分:
# Terminal tab name in gnome-terminal or Guake
PROMPT_COMMAND='echo -ne "\033]0;$(basename ${PWD})\007"'
GIT_PS1_SHOWCOLORHINTS=yes
RET=\$?
source /usr/lib/git-core/git-sh-prompt
if [ "$color_prompt" = yes ]; then
color_reset=$(tput sgr0)
color_bold=$(tput bold)
color_white=$(tput setaf 7)
color_jobs=$(tput setaf 7)
color_user=$(tput setaf 3)
color_dir=$(tput setaf 4)
color_load=$(tput setaf 5)
color_succeed=$(tput setaf 2)
color_fail=$(tput setaf 1)
sep=$(tput setaf 7)\)
PS1="${color_user}\u${sep}\[\D{%T}\]${sep}${color_reset}\$(__git_ps1)${color_dir}\W${color_reset}${sep}\`if [[ ${RET} == 0 ]]; then echo \"${color_succeed}0\"; else echo \"${color_fail}${RET}\"; fi\`${color_white}${sep}${color_reset}\$ "
else
PS1="\u${sep}\[\D{%T}\]${sep}\$(__git_ps1)\W${sep}\`if [[ ${RET} == 0 ]]; then echo \"0\"; else echo \"${RET}\"; fi\`${sep}\$ "
fi
这是正在使用的命令行示例:
snim2)10:39:53)dirname)0)$ cd scratch
snim2)10:39:54)scratch)0)$ git init
Initialised empty Git repository in .../scratch/.git/
snim2)10:39:56) (master)scratch)0)$ asdasda
asdasda: command not found
snim2)10:40:05) (master)scratch)1)$ $?
127: command not found
snim2)10:40:10) (master)scratch)1)$
如您所见,当命令的返回码不为零时,它会显示1)
在提示符中,而不是显示正确的返回码——在这种情况下127)
。如何解决这个问题?
解决方案
你做:
..$(__git_ps1)...\`if [[ $? == 0 ]];
这$?
将是__git_ps1
不是命令行上最后执行的命令的返回状态。
尝试立即将退出返回值保存在第一个命令替换块中:
if [ "$color_prompt" = yes ]; then
color_reset=$(tput sgr0)
color_bold=$(tput bold)
color_white=$(tput setaf 7)
color_jobs=$(tput setaf 7)
color_user=$(tput setaf 3)
color_dir=$(tput setaf 4)
color_load=$(tput setaf 5)
color_succeed=$(tput setaf 2)
color_fail=$(tput setaf 1)
sep=$(tput setaf 7)\)
else
color_reset=
color_bold=
color_white=
color_jobs=
color_user=
color_dir=
color_load=
color_succeed=
color_fail=
sep=\) # remove the braces...
fi
# note the quotes - "" expand at setting time, '' expand at runtime
PS1=
PS1+="${color_user}\u${sep}\[\D{%T}\]${sep}${color_reset}"
PS1+='$('
PS1+='ret=$?; ' # first thing we do - save the exit return value
PS1+='__git_ps1; '
PS1+='printf "%s" "'
PS1+="${color_dir}\W${color_reset}${sep}"
PS1+='"; '
PS1+='if ((ret == 0)); then '
PS1+='printf "%s" "'
PS1+="${color_succeed}" # expand variable on assignment side
PS1+='0"; ' # this looks strange. Just print first the color, then $ret...
PS1+='else '
PS1+='printf "%s" "'
PS1+="$color_fail"
PS1+='$ret"; '
PS1+='fi '
PS1+=')'
PS1+="${color_white}${sep}${color_reset}"
PS1+='\$ ' # note - this is *not* "\$ "
推荐阅读
- kubernetes - Kubeflow - create_run_from_pipeline_func 中的错误
- java - 合并排序是否有最好或最坏的情况?
- azure - 无法使用 GitHub 操作部署到 Azure 容器 - 部署失败并出现错误:错误:无法获取应用运行时操作系统
- git - 如何提取我的分叉远程源仓库中尚不存在的上游分支?
- javascript - 在删除包含 vue 根元素的父 dom 元素之前,是否必须卸载 Vue.js 3 应用程序?
- discord.js - 如何让我的机器人在公告类型的频道不和谐中发送消息?
- matlab - 使用 MATLAB(不使用机器学习)使用 LiDAR (velodyne) 进行对象检测和跟踪
- python - 共享 google drive API 的 .json 文件是否安全?
- python - 如何使用 for 循环绘制多个子图?
- android - 两个应用程序如何通过 Firebase 预测更改单个 Firebase 远程配置变量?