PS1定义中的条件pwd [英] Conditional pwd in an PS1 definition

查看:152
本文介绍了PS1定义中的条件pwd的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在symlink中,我想在提示符下显示当前工作目录.

I want to display the current working directory in my prompt differently if I am in a symlink than not.

我到目前为止:

[[ `pwd -P` = `pwd` ]] && echo "\[1;31m\]$(pwd -P)" || echo "\[1;32m\]$(pwd)"

将返回所需的输出,但不能代替命令提示符中的\w.

will return the desired output but it will not work as a replacement for \w in the command prompt.

我尝试用反引号将其包装起来,但这只会在PS1中产生pwd -Ppwd.

I tried wrapping it with backticks but that just results in pwd -Ppwd in the PS1.

如果不是symlink,我想有条件地更改颜色和值,这就是为什么我要做出 if/else 类型决定的原因.

I want to conditionally change the color and the value if it is a symlink or not which is why I want the if/else type decision.

推荐答案

这就是我最终得到的结果:

我想更改pwd的值以及symlink时的颜色.

This is what I ended up with:

I wanted to change the pwd value as well as the color when it is a 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
}

这篇关于PS1定义中的条件pwd的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆