ICode9

精准搜索请尝试: 精确搜索
首页 > 系统相关> 文章详细

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

2019-06-12 20:48:48  阅读:268  来源: 互联网

标签:bash shell unix linux command-prompt


我必须在根文件系统下的三个主目录中工作 – 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='\[\033[01;32m\]\u@\h:\w\[\033[00m\]\$'
    elif [[ "$pwd/" =~ ^/etc/ ]] ; then
        PS1='\[\033[01;34m\]\u@\h:\w\[\033[00m\]\$'
    elif [[ "$pwd/" =~ ^/tmp/ ]] ; then
        PS1='\[\033[01;33m\]\u@\h:\w\[\033[00m\]\$'
    else
        PS1='\u@\h:\w\\$'
    fi
    export PS1
}


# checking directory and setting prompt on shell startup
color_prompt

标签:bash,shell,unix,linux,command-prompt
来源: https://codeday.me/bug/20190612/1228138.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有