Shell prompt that is based on location in filesystem

前端 未结 2 1399
遇见更好的自我
遇见更好的自我 2020-12-10 19:14

I have to work within three main directories under the root filesystem - home/username, project, and scratch. I want my shell prompt to display which of these top level dire

2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-10 19:57

    You can hook into cd to change the prompt every time you are changing the working directory. I've asked myself often how to hook into cd but I think that I now found a solution. What about adding this to your ~/.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
    

提交回复
热议问题