我必须在根文件系统下的三个主目录中工作 – 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