11.10. 控制 $PWD 的大小和外观

Unix 允许长文件名,这可能导致 $PWD 的值非常长。有些人(特别是默认的 RedHat 提示符)选择使用当前工作目录的基本名称(例如,如果 $PWD="/home/giles",则为 "giles")。我喜欢比这更多的信息,但通常希望限制目录名称的长度,并且从左侧截断是最合理的。

#   How many characters of the $PWD should be kept
local pwdmaxlen=30
#   Indicator that there has been directory truncation:
#trunc_symbol="<"
local trunc_symbol="..."
if [ ${#PWD} -gt $pwdmaxlen ]
then
	local pwdoffset=$(( ${#PWD} - $pwdmaxlen ))
	newPWD="${trunc_symbol}${PWD:$pwdoffset:$pwdmaxlen}"
else
	newPWD=${PWD}
fi

上面的代码可以作为 PROMPT_COMMAND 的一部分执行,并且可以生成环境变量(newPWD)然后可以包含在提示符中。感谢 Alexander Mikhailian他重写了代码以利用新的 Bash 功能,从而大大加快了速度。

Risto Juola (risto AT risto.net) 写道,他更喜欢在$newPWD中包含 "~",因此他编写了另一个版本

pwd_length=20

DIR=`pwd`

echo $DIR | grep "^$HOME" >> /dev/null

if [ $? -eq 0 ]
then
  CURRDIR=`echo $DIR | awk -F$HOME '{print $2}'`
  newPWD="~$CURRDIR"

  if [ $(echo -n $newPWD | wc -c | tr -d " ") -gt $pwd_length ]
  then
    newPWD="~/..$(echo -n $PWD | sed -e "s/.*\(.\{$pwd_length\}\)/\1/")"
  fi
elif [ "$DIR" = "$HOME" ]
then
  newPWD="~"
elif [ $(echo -n $PWD | wc -c | tr -d " ") -gt $pwd_length ]
then
  newPWD="..$(echo -n $PWD | sed -e "s/.*\(.\{$pwd_length\}\)/\1/")"
else
  newPWD="$(echo -n $PWD)"
fi

相对速度:第一个版本在未加载的 486SX25 上大约需要 0.45 秒。Risto 的版本大约需要 0.80 到 0.95 秒。在这种情况下,变化是由于是否需要截断。