PS1定义中的条件转发

时间:2018-04-17 15:40:45

标签: bash ps1

如果我在symlink而非[[ `pwd -P` = `pwd` ]] && echo "\[1;31m\]$(pwd -P)" || echo "\[1;32m\]$(pwd)" ,我想以不同方式显示当前工作目录

我到目前为止:

\w

将返回所需的输出,但它不能在命令提示符中替换pwd -Ppwd

我尝试用反引号包装它,但这只会导致PS1中的symlink

我想有条件地更改颜色和值,如果它是public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, [FromServices]IConfiguration configuration) : base(options) { } ,这就是我想要 if / else 类型决定的原因。

2 个答案:

答案 0 :(得分:4)

如果你想让它实际上高效(并提示快速渲染!),那么你将要缓存物理查找,并使用{ {1}}而非$PWD为逻辑的。

$(pwd)

答案 1 :(得分:1)

这就是我最终的结果:

我希望更改pwd值以及symlink时的颜色。

# look up color codes for our terminal rather than assuming ANSI
declare -r red=$(tput setaf 1)
declare -r green=$(tput setaf 2)
declare -r white=$(tput setaf 9)
declare -r aqua=$(tput setaf 6)
declare -r reset=$(tput sgr0)

colorize_msg() {
   printf -v $1 "\[%s\]%s" ${2} ${3}
}

set_prompt() {

    declare prompt_pwd=""
    # only rerun this code when changing directories!
    if [[ last_prompt_pwdL != $PWD ]]; then
        declare -g last_prompt_pwdL=$PWD # logical path
        declare -r last_prompt_pwdP=$(pwd -P) # physical path
        if [[ $last_prompt_pwdL = $last_prompt_pwdP ]]; then
          colorize_msg prompt_pwd $green $last_prompt_pwdL
        else
          colorize_msg prompt_pwd $red $last_prompt_pwdP
        fi

        # ...actually could have just "return"ed above, but this way we can change other
        # aspects of the prompt even when we don't need to do a new directory lookup.
        declare prompt=""
        declare msg=""
        colorize_msg msg $white "["
        prompt+=$msg
        colorize_msg msg $aqua "\u"
        prompt+=$msg
        colorize_msg msg $red "@"
        prompt+=$msg
        colorize_msg msg $aqua"\h"
        prompt+=$msg
        colorize_msg msg $white "] ["
        prompt+=$msg
        prompt+=${prompt_pwd}
        colorize_msg msg $white "]"
        prompt+=$msg
        prompt+="${reset}\n"
        PS1=$prompt
    fi
}