我必须在根文件系统下的三个主目录中工作——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) : '
不幸的是,这并没有像我想要的那样起作用。当我在主目录中时,我会得到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='[ 33[01;32m]u@h:w[ 33[00m]$ '
elif [[ "$pwd/" =~ ^/etc/ ]] ; then
PS1='[ 33[01;34m]u@h:w[ 33[00m]$ '
elif [[ "$pwd/" =~ ^/tmp/ ]] ; then
PS1='[ 33[01;33m]u@h:w[ 33[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
如果它不起作用,请尝试将__DIR=$PWD
更改为__DIR=$(pwd)
,并告诉我们它是否也有帮助。我还想确认您是否真的在运行bash
。请注意,sh
有许多变体,如bash
、zsh
、ksh
和dash
,默认安装和使用的变体取决于每个系统。要确认您正在使用Bash,请执行echo "$BASH_VERSION"
并查看它是否显示消息。
您还应该确保使用单引号而不是双引号运行export PS1='$(top_level_dir) : '
:export PS1="$(top_level_dir) : "
。