问题
My current PS1:
PS1='\[\033]0;$TITLEPREFIX:${PWD//[^[:ascii:]]/?}\007\]\n\[\033[32m\]\u@\h \[\033[35m\]`date +%Y-%m-%d,%H:%M:%S` \[\033[33m\]\w\[\033[36m\]`__git_ps1`\[\033[0m\]\n$: '
Yes, it's a mess, but it serves me well - my prompts look like this:
P2759474@RVPTINTCL415MQC 2017-10-06,11:20:18 ~/repos/jdk (master)
They are even color coded, with user@machine in green, timestamp in purple, current location in yellow, and any git branch in blue. I'm just a little annoyed that I have to use backticks instead of a $()
construct.
Anyone know why? Willing to help me understand it? It's only a problem when parsing complex prompt values with subshell commands, and only a problem then because I want to understand why it matters there... General improvement suggestions always welcome while we're at it.
Update -
Currently when I try to use $() I get a lot of
bash: command substitution: line 1: syntax error near unexpected token ')'
bash: command substitution: line 1: 'date +%Y-%m-%d,%H:%M:%S)'
bash: command substitution: line 1: syntax error near unexpected token ')'
bash: command substitution: line 1: '__git_ps1)'
My env has
BASH_VERSINFO=([0]="4" [1]="3" [2]="42" [3]="5" [4]="release" [5]="x86_64-pc-msys")
BASH_VERSION='4.3.42(5)-release'
[ -z "$BASH_VERSION" ] || shopt -q promptvars || ps1_expanded=no;
That tells me something, maybe... Thanks!
回答1:
When you start trying to embed commands in your prompt, it is time to start using PROMPT_COMMAND
.
# You won't even have to put the title-bar stuff in your prompt
# and there are already shortcuts for date and time
set_titlebar () {
printf '\033]0;%s:%s\007' "$TITLEPREFIX" "${PWD//[^[:ascii:]]/?}"
}
set_prompt () {
PS1='\[\033[32m\]\u@\h ' # user@host in green
PS1+='\[\033[35m\]\D{%Y-%m-%d},\t ' # Don't need date
PS1+='\[\033[33m\]\w\[\033[36m\]' # Directory in orange
PS1+=$(__git_ps1) # git info, if appropriate
PS1+='\[\033[0m\]\n$: '
}
PROMPT_COMMAND='set_titlebar;set_prompt'
来源:https://stackoverflow.com/questions/46610384/why-cant-i-use-in-ps1-instead-of-backticks