2016-05-24 18 views
1

我有我的bash提示符,如下面的脚本定义 -有时光标跳到行首在bash提示符

#!/bin/bash 

if tput setaf 1 &> /dev/null; then 
    tput sgr0; # reset colors 
    bold=$(tput bold); 
    reset=$(tput sgr0); 
    black=$(tput setaf 235) 
    red=$(tput setaf 1) 
    green=$(tput setaf 142) 
    yellow=$(tput setaf 214) 
    blue=$(tput setaf 66) 
    purple=$(tput setaf 175) 
    cyan=$(tput setaf 37) 
    gray=$(tput setaf 246) 
    white=$(tput setaf 223) 
    orange=$(tput setaf 208) 
else 
    bold=''; 
    reset="\e[0m"; 
    black="\e[1;30m"; 
    blue="\e[1;34m"; 
    cyan="\e[1;36m"; 
    green="\e[1;32m"; 
    orange="\e[1;33m"; 
    purple="\e[1;35m"; 
    red="\e[1;31m"; 
    violet="\e[1;35m"; 
    white="\e[1;37m"; 
    yellow="\e[1;33m"; 
fi; 

# Highlight the user name when logged in as root. 
if [[ "$USER" == "root" ]]; then 
    userStyle="$red"; 
else 
    userStyle="$orange"; 
fi; 

# Highlight the hostname when connected via SSH. 
if [[ "$SSH_TTY" ]]; then 
    hostStyle="$green"; 
else 
    hostStyle="$gray"; 
fi; 

dirStyle="$cyan" 

function prompt_command { 
    ret_code=$? 
    # Are we running in a shell invoked from Vim? 
    if [[ "$VIM" ]]; then 
     vim="(Vim) " 
    else 
     vim="" 
    fi 

    # Did last command return non-zero value? 
    if [ "$ret_code" != 0 ]; then 
     ret_str="\[$red\]$ret_code>" 
    else 
     ret_str="\[$green\]$" 
    fi 

    PS1="\[$userStyle\]\u \[$reset\]at \[$hostStyle\]\H \[$reset\]in \[$dirStyle\]\w\n\[$yellow\]$vim$ret_str\[$reset\] " 
} 
export PROMPT_COMMAND=prompt_command 
export PS2="\[$blue\]continue -> \[$reset\]" 

它很简单,只需用户名,主机名,当前目录和几个变量 - 一个检查如果从vim调用shell,而其他则是最后一个命令的返回码。

有时光标会跳到行首,当我尝试完成标签页时。在发生这种情况时,我一直无法找到模式。

这是提示的样子 -

rogandhi at sjc-ads-253 in ~/tools 
$ 
rogandhi at sjc-ads-253 in ~/tools 
$ adsf 
-bash: adsf: command not found 
rogandhi at sjc-ads-253 in ~/tools 
127> 

貌似这个当外壳由VIM调用 -

rogandhi at sjc-ads-253 in ~/tools 
(Vim) $ 
rogandhi at sjc-ads-253 in ~/tools 
(Vim) $ asdf 
bash: asdf: command not found 
rogandhi at sjc-ads-253 in ~/tools 
(Vim) 127> 

以下是declare -p PS1

rogandhi at sjc-ads-253 in ~/tools 
$ declare -p PS1 
declare -- PS1="\\[\\]\\u \\[\\]at \\[\\]\\H \\[\\]in \\[\\]\\w\\n\\[\\]\\[\\]\$\\[\\] " 

任何输出想法?我如何去调试这种行为?

+0

为什么周围的换行有括号? –

+0

当您设置'PS1 =“>>>”'时,是否会发生这种情况? – hek2mgl

+0

@ IgnacioVazquez-Abrams当我在'\ n'周围添加括号时,光标跳转发生得不那么频繁。 – ronakg

回答

1

问题是行ret_str="\[$green\]$"未被转义。

\转义$解决了这个问题。

修复:

ret_str="\[$green\]\$"