我正在寻找一个bash函数,该函数将缩短长路径名,以防止PS1变量过长。类似于以下内容:
/this/is/the/path/to/a/really/long/directory/i/would/like/shortened
可能最终会变成:
/t../i../t../p../to/a/r../l../d../i/w../like/shortened
对于我的.bashrc文件,采用所需的路径以及可以缩短的最大可接受字符数将是完美的选择。
最佳答案
Python脚本怎么样?这将首先缩短最长的目录名称,一次缩短一个字符,直到达到其长度目标或无法获得更短的路径。它不会缩短路径中的最后一个目录。
(我开始用普通的shell脚本编写此代码,但是人,bash讨厌字符串操作。)
#!/usr/bin/env python
import sys
try:
path = sys.argv[1]
length = int(sys.argv[2])
except:
print >>sys.stderr, "Usage: $0 <path> <length>"
sys.exit(1)
while len(path) > length:
dirs = path.split("/");
# Find the longest directory in the path.
max_index = -1
max_length = 3
for i in range(len(dirs) - 1):
if len(dirs[i]) > max_length:
max_index = i
max_length = len(dirs[i])
# Shorten it by one character.
if max_index >= 0:
dirs[max_index] = dirs[max_index][:max_length-3] + ".."
path = "/".join(dirs)
# Didn't find anything to shorten. This is as good as it gets.
else:
break
print path
输出示例:
$ echo $DIR
/this/is/the/path/to/a/really/long/directory/i/would/like/shortened
$ ./shorten.py $DIR 70
/this/is/the/path/to/a/really/long/directory/i/would/like/shortened
$ ./shorten.py $DIR 65
/this/is/the/path/to/a/really/long/direc../i/would/like/shortened
$ ./shorten.py $DIR 60
/this/is/the/path/to/a/re../long/di../i/would/like/shortened
$ ./shorten.py $DIR 55
/t../is/the/p../to/a/r../l../di../i/wo../like/shortened
$ ./shorten.py $DIR 50
/t../is/the/p../to/a/r../l../d../i/w../l../shortened
关于linux - bash PWD缩短,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1616678/