ico*_*ast 3 directory find shell-script files
我想找到一种通过在目录结构中向上查找来查找给定文件的方法,而不是递归搜索子目录。
有一个node 模块似乎完全符合我的要求,但我不想依赖于安装 JavaScript 或类似的包。是否有针对此的 shell 命令?有办法find做到这一点吗?或者我无法通过谷歌搜索找到的标准方法?
这是通用 shell 命令中find-config 算法的直接翻译(在 bash、ksh 和 zsh 下测试),其中我使用返回码 0 表示成功,使用 1 表示 NULL/失败。
findconfig() {
# from: https://www.npmjs.com/package/find-config#algorithm
# 1. If X/file.ext exists and is a regular file, return it. STOP
# 2. If X has a parent directory, change X to parent. GO TO 1
# 3. Return NULL.
if [ -f "$1" ]; then
printf '%s\n' "${PWD%/}/$1"
elif [ "$PWD" = / ]; then
false
else
# a subshell so that we don't affect the caller's $PWD
(cd .. && findconfig "$1")
fi
}
Run Code Online (Sandbox Code Playgroud)
示例运行,从Stephen Harris的回答中复制并扩展了被盗的设置:
$ mkdir -p ~/tmp/iconoclast
$ cd ~/tmp/iconoclast
$ mkdir -p A/B/C/D/E/F A/good/show
$ touch A/good/show/this A/B/C/D/E/F/srchup A/B/C/thefile
$ cd A/B/C/D/E/F
$ findconfig thefile
/home/jeff/tmp/iconoclast/A/B/C/thefile
$ echo "$?"
0
$ findconfig foobar
$ echo "$?"
1
Run Code Online (Sandbox Code Playgroud)