Linux 基于文件系统中的位置的Shell提示符
我必须在根文件系统下的三个主要目录中工作——home/username、project和scratch。我想让shell提示符显示我所在的顶级目录 以下是我试图做的:Linux 基于文件系统中的位置的Shell提示符,linux,bash,shell,unix,command-prompt,Linux,Bash,Shell,Unix,Command Prompt,我必须在根文件系统下的三个主要目录中工作——home/username、project和scratch。我想让shell提示符显示我所在的顶级目录 以下是我试图做的: top_level_dir () { if [[ "${PWD}" == *home* ]] then echo "home"; elif [[ "${PWD}" == *scratch* ]] then echo "scratch"; elif [[ "${
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) : '
不幸的是,这不是我想要的工作。当我在我的主目录中时,我会得到
home:
提示,但是如果我切换到scratch或projects,则提示不会改变。我不太理解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
请尝试此方法,并告诉我们其工作原理,例如,您的提示符如何更改主目录、项目或临时目录以及除此之外的其他目录。告诉我们您还看到了哪些错误消息。问题就在其中 如果是通过脚本、直接执行或通过像~/.bashrc这样的启动脚本,请告诉我如何运行它
top_level_dir ()
{
__DIR=$PWD
case "$__DIR" in
*home*)
echo home
;;
*scratch*)
echo scratch
;;
*project*)
echo project
;;
*)
echo "$__DIR"
;;
esac
}
export PS1='$(top_level_dir) : '
export -f top_level_dir
如果它不起作用,请尝试将\uuu DIR=$PWD
更改为\uuu DIR=$(PWD)
,并告诉我们它是否也有帮助。我还想确认您是否真的在运行bash
。请注意,sh
有许多变体,如bash
、zsh
、ksh
和dash
,默认情况下安装和使用的变体取决于每个系统。要确认您正在使用Bash,请执行echo“$Bash\u VERSION”
并查看它是否显示消息
您还应该确保正在使用单引号而不是双引号运行
export PS1=“$(top\u level\u dir):”
export PS1=“$(top\u level\u dir):“在切换到scratch/project之后,您是否再次执行了export PS1=…
行?对我有效。你运行什么版本的bash?@choroba它在bash4.2.42上对我也有效。它在4.1.2中不起作用。这有意义吗?你检查单引号是对的。谢谢实际上我用的是双引号。我的代码在更改为单引号后工作。它现在在4.2版和4.1版上都能正常工作。我的代码解决了这个问题,请参阅我对konsolebox答案的评论。我喜欢你用钩子改变颜色的解决方案,我会用它的@迪帕克:好的。我的答案有点变了。我会研究你的解决方案。但是,你的问题很好。曾经认为这是不可能的