通常,长路径会被错误输入,或者您会收到一条路径不存在的日志文件条目。是否有命令或 shell 函数可以导航路径层次结构,直到找到匹配的路径?
命令行交换可以像这样:
$ ls /var/lib/my/supper/complicated/path
File or directory not found
$ fixpath /var/lib/my/supper/complicated/path
Found /var/lib/my
作为一个奖励功能,相似性检测会很棒:
$ fixpath /var/lib/my/supper/complicated/path
Found /var/lib/my
Did you mean /var/lib/my/super/complicated/path
答案1
$ fixpath /home/user/docus/collection/unix/djakl/jfkdsl/dfjksld/fsdkl
Found /home/user/docus/collection/unix
$ type fixpath
fixpath is a function
fixpath ()
{
CURDIR="$PWD";
DIR="$1";
E=1;
while [ $E -eq 1 ]; do
cd "$DIR" 2> /dev/null && {
E=0;
echo Found "$DIR"
} || {
DIR="${DIR%/*}";
DIR="${DIR:-/}"
};
done;
cd "$CURDIR"
}
大多数现代 shell 都可以自行进行相似性自动更正。至少 bash 和 zsh 是这样。
答案2
以下 shell 函数采用路径名并确定实际存在的最长位。它通过从路径中删除最后一个路径元素来实现此目的,直到路径完全为空,或者它对应于实际存在的文件(或目录或任何内容)。
fixpath () (
pathname="$1"
while [ -n "$pathname" ] && [ ! -e "$pathname" ]; do
pathname=${pathname%/*}
case "$pathname" in
*/*) continue ;;
*) [ -e "$pathname" ] || pathname=''
break
esac
done
printf 'Longest existing path in "%s" is "%s"\n' "$1" "$pathname"
)
在不包含 a 的case
情况下需要该语句来终止循环(这意味着它不会被变量替换修改)。这可以避免某些情况下的无限循环。$pathname
/
测试它:
$ fixpath /home/kk/blaha/123
Longest existing path in "/home/kk/blaha/123" is "/home/kk"
$ fixpath "$HOME/.profile"
Longest existing path in "/home/kk/.profile" is "/home/kk/.profile"
$ fixpath "n"
Longest existing path in "n" is ""