使用 bash
,我如何在当前目录的上层目录树中查找具有特定名称的文件?
更明确地说,我想查找位于我的工作目录根目录中的文件,但是我不知道根目录在哪里,而且我的 pwd
可能在根目录下面的任何位置。
在根目录查找file.txt
x=`pwd`
while [ "$x" != "/" ] ; do
x=`dirname "$x"`
find "$x" -maxdepth 1 -name file.txt
done
x=`pwd`; while [ "$x" != "/" ] ; do x=`dirname "$x"`; echo "$x"; if [ `find "$x" -maxdepth 1 -name erm.properties` ]; then break; fi; done
- Niel de Wetlocal DIR=$(pwd)
while [ ! -z "$DIR" ] && [ ! -f "$DIR/myFile.txt" ]; do
DIR="${DIR%\/*}"
done
echo $DIR/myFile.txt
DIR = $(realpath $PWD)
- Marcel Sonderegger我在我的~/.bashrc文件中定义了以下函数:
dnif () {
# Recursively list a file from PWD up the directory tree to root
[[ -n $1 ]] || { echo "dnif [ls-opts] name"; return 1; }
local THERE=$PWD RC=2
while [[ $THERE != / ]]
do [[ -e $THERE/${2:-$1} ]] && { ls ${2:+$1} $THERE/${2:-$1}; RC=0; }
THERE=$(dirname $THERE)
done
[[ -e $THERE/${2:-$1} ]] && { ls ${2:+$1} /${2:-$1}; RC=0; }
return $RC
}
该命令将在当前目录到根目录的每个目录中搜索您提供的名称,并进行列表化显示,同时可使用您提供的可选 ls -options。例如输出:
me@host:~/dev/example
$ dnif; echo $?
dnif [ls-opts] name
1
me@host:~/dev/example
$ dnif -alp nonesuch; echo $?
2
me@host:~/dev/example
$ dnif -alp .bashrc; echo $?
-rw-r--r-- 1 me mine 3486 Apr 3 2012 /home/me/.bashrc
0
me@host:~/dev/example
$ dnif -d .
/home/me/dev/example/.
/home/me/dev/.
/home/me/.
/home/.
/.
root
用户身份运行find / -name <filename>
命令来搜索整个系统。 - Eugene S