问题描述
我要在根文件系统下的三个主要工作目录 - 家居/用户名,项目和划伤。我希望我的shell提示符下显示这些顶层目录我在
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 directories i am in.
下面就是我要做的:
top_level_dir ()
{
if [[ "${PWD}" == *home* ]]
then
echo "home";
elif [[ "${PWD}" == *scratch* ]]
then
echo "scratch";
elif [[ "${PWD}" == *project* ]]
then
echo "project";
fi
}
然后,我出口PS1为:
Then, I export PS1 as:
export PS1='$(top_level_dir) : '
可惜,这是行不通的,因为我想要的。我得到首页
我的提示,当我在我的主目录,但如果我切换到划伤或项目,然后提示不会改变。我不明白bash脚本编程得非常好,所以我会AP preciate任何帮助纠正我的code。
Unfortunately this is not working as I want. I get home :
for my prompt when I am in my home directory, but if I switch to scratch or projects then the prompt does not change. I do not understand bash scripting very well so I would appreciate any help to correct my code.
推荐答案
您可以挂接到 CD
来要更改的工作目录的提示每一次改变。我问自己经常如何挂钩到 CD
,但我认为我现在找到了解决办法。怎么样添加以下内容到〜/ .bashrc中
?:
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
这篇关于即基于位置的文件系统shell提示符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!