修剪终端命令提示符工作目录

在深文件夹结构中使用终端时,有时提示可占用大部分行。 有什么办法可以修剪工作目录吗? 我知道我能做到

PS1="\W >" 

只打印当前目录,而不是完整路径,但有没有办法,如下所示:

 /home/smauel/de...ther/folder > 

创建一个小python脚本,实现所需的修剪逻辑。

示例: ~/.short.pwd.py

 import os from socket import gethostname hostname = gethostname() username = os.environ['USER'] pwd = os.getcwd() homedir = os.path.expanduser('~') pwd = pwd.replace(homedir, '~', 1) if len(pwd) > 33: pwd = pwd[:10]+'...'+pwd[-20:] # first 10 chars+last 20 chars print '[%s@%s:%s] ' % (username, hostname, pwd) 

现在从终端测试它:

 export PROMPT_COMMAND='PS1="$(python ~/.short.pwd.py)"' 

如果您对结果没问题,只需将命令附加到~/.bashrc

如果你使用bash4(Ubuntu 9.10和更新版本有bash4),最简单的选择就是设置PROMPT_DIRTRIM变量。 例如:

 PROMPT_DIRTRIM=2 

对于一个类似于JoãoPinto的例子,(它可以在较旧的bash版本中工作,并确保路径组件永远不会超过30个字符),你可以这样做:

 PS1='[\u@\h:$(p=${PWD/#"$HOME"/~};((${#p}>30))&&echo "${p::10}…${p:(-19)}"||echo "\w")]\$ ' 

解决该问题的另一种方法是在PS1中包含换行符,以便工作目录和实际提示出现在单独的行中,例如:

 PS1="\w\n>" 

将它添加到~/.bashrc的底部

 split_pwd() { # Only show ellipses for directory trees -gt 3 # Otherwise use the default pwd as the current \w replacement if [ $(pwd | grep -o '/' | wc -l) -gt 3 ]; then pwd | cut -d'/' -f1-3 | xargs -I{} echo {}"/../${PWD##*/}" else pwd fi } export PS1="\$(split_pwd) > " 

不可否认,这可能更干净,但我想得到一个解决方案。

目录的预期输出超过三层深。

 /home/chris/../Node Projects > 

桌面和后面目录的预期输出。

 /home/chris/Desktop > /home/chris > /home 

我最喜欢这个, PS1="[\W]\\$ "

当你运行workon命令时,@joão-pinto的优秀答案的这一小小补充增加了虚拟环境名称。

 import os from platform import node hostname = node().split('.')[0] username = os.environ['USER'] pwd = os.getcwd() homedir = os.path.expanduser('~') pwd = pwd.replace(homedir, '~', 1) # check for the virtualenv ve = os.getenv('VIRTUAL_ENV') if ve: venv = '(`basename \"$VIRTUAL_ENV\"`)' else: venv = '' if len(pwd) > 33: pwd = pwd[:10]+'...'+pwd[-20:] # first 10 chars+last 20 chars print '%s[%s@%s:%s] ' % (venv, username, hostname, pwd) 

根据Cris Sullivan的回答,但保留~文件夹

 get_bash_w() { # Returns the same working directory that the \W bash prompt command echo $(pwd | sed 's@'"$HOME"'@~@') } split_pwd() { # Split pwd into the first element, elipsis (...) and the last subfolder # /usr/local/share/doc --> /usr/.../doc # ~/project/folder/subfolder --> ~/project/../subfolder split=2 W=$(get_bash_w) if [ $(echo $W | grep -o '/' | wc -l) -gt $split ]; then echo $W | cut -d'/' -f1-$split | xargs -I{} echo {}"/../${W##*/}" else echo $W fi }