Skip to content

Instantly share code, notes, and snippets.

@snoire
Last active March 10, 2025 02:16
Show Gist options
  • Select an option

  • Save snoire/9cf8fd0d8a7fe7c2c28e57fa45da1916 to your computer and use it in GitHub Desktop.

Select an option

Save snoire/9cf8fd0d8a7fe7c2c28e57fa45da1916 to your computer and use it in GitHub Desktop.
pathshorten() {
local parts=() # 用于存储缩短后的路径部分
local head=${(%):-"%-1~"} # ${(%):-word} 把 word 展开
local tail=${${(D)PWD}#$head} # ${(D)PWD} 缩短替换目录
if [[ $1 == '-u' ]] { # 尝试找到每个目录部分的唯一最短前缀,确保路径的唯一性
local base=${~head} # 展开为实际路径(不能加双引号!!)
# 将 tail 按 '/' 分割,并处理每一部分
# 空 tail 则替换成 '/',因为之后要用 ':h' 处理。"/":h 为空,而 "":h 为 "."
for dir (${(s./.)${tail:-/}:h}) {
local short='' # 用于存储当前目录部分的缩短形式
# 遍历当前目录的每个字符,直到找到一个唯一的匹配项
for i ({1..$#dir}) {
short+=$dir[$i]
matching=($base/$short*(/N))
if (( $#matching == 1 )) {
break
}
}
parts+=/$short
base+="/$dir"
}
} else { # 将路径的每一部分缩短为第一个字符
# 将 tail 按 '/' 分割,并处理每一部分
for dir (${(s./.)${tail:-/}:h}) {
parts+=/$dir[1]
}
}
print "$head${(j..)parts}${tail:+/${PWD:t}}"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment