加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

linux – 基于文件系统中的位置的Shell提示

发布时间:2020-12-14 00:29:48 所属栏目:Linux 来源:网络整理
导读:我必须在根文件系统下的三个主目录中工作 – home / username,project和scratch.我希望我的 shell提示符显示我所在的这些顶级目录. 这是我想要做的: top_level_dir (){ if [[ "${PWD}" == *home* ]] then echo "home"; elif [[ "${PWD}" == *scratch* ]] th
我必须在根文件系统下的三个主目录中工作 – home / username,project和scratch.我希望我的 shell提示符显示我所在的这些顶级目录.

这是我想要做的:

top_level_dir ()
{
    if [[ "${PWD}" == *home* ]]
    then
        echo "home";
    elif [[ "${PWD}" == *scratch* ]]
    then
        echo "scratch";
    elif [[ "${PWD}" == *project* ]]
    then
        echo "project";
    fi

}

然后,我导出PS1为:

export PS1='$(top_level_dir) : '

不幸的是,这不符合我的要求.我回到家:因为我在我的主目录中的提示,但如果我切换到临时或项目,则提示不会改变.我不太了解bash脚本,所以我很感激任何帮助来纠正我的代码.

解决方法

您可以挂钩到cd以在每次更改工作目录时更改提示.我经常问自己如何挂入cd,但我认为我现在找到了解决方案.把它添加到?/ .bashrc怎么样?:

#
# Wrapper function that is called if cd is invoked
# by the current shell
#
function cd {
    # call builtin cd. change to the new directory
    builtin cd $@
    # call a hook function that can use the new working directory
    # to decide what to do
    color_prompt
}

#
# Changes the color of the prompt depending
# on the current working directory
#
function color_prompt {
    pwd=$(pwd)
    if [[ "$pwd/" =~ ^/home/ ]] ; then
        PS1='[33[01;32m]u@h:w[33[00m]$'
    elif [[ "$pwd/" =~ ^/etc/ ]] ; then
        PS1='[33[01;34m]u@h:w[33[00m]$'
    elif [[ "$pwd/" =~ ^/tmp/ ]] ; then
        PS1='[33[01;33m]u@h:w[33[00m]$'
    else
        PS1='u@h:w$'
    fi
    export PS1
}


# checking directory and setting prompt on shell startup
color_prompt

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读