弹出当前目录直到找到特定文件

弹出当前目录直到找到特定文件

我有兴趣编写具有以下行为的脚本:

  1. 查看当前目录中是否存在文件 build.xml,如果存在,则运行通过脚本参数提供的命令。
  2. 如果不是,则弹出当前目录并查看父目录。转到 1。

一旦找到文件或到达根目录,脚本就会结束。此外,一旦脚本完成并将控制权返回给用户,我希望当前目录是脚本最初所在的目录

我不太熟悉 shell 脚本,但如果能提供任何帮助/指导我将非常感激。

答案1

在 bash 中,你可以像这样实现这一点:

市场营销网

curr=`pwd`
file_name=build.xml
echo "Current directory: $curr"
while [ "$curr" != "/" ]; do
  echo "Processing: $curr"
  file="$curr/$file_name"
  if [ -f "$file" ]; then
    echo "Found at: $file, running command..."
    cd "$curr"
    "$@"
    exit
  fi
  curr="`dirname \"$curr\"`"
done
echo "$file_name not found."

示例运行:

~$ cd /tmp
/tmp$ ls mkt.sh
mkt.sh
/tmp$ mkdir -p a/b/c/d
/tmp$ echo hello > a/build.xml
/tmp$ find a
a
a/build.xml
a/b
a/b/c
a/b/c/d
/tmp$ cd a/b/c/d
/tmp/a/b/c/d$ /tmp/mkt.sh cat build.xml
Current directory: /tmp/a/b/c/d
Processing: /tmp/a/b/c/d
Processing: /tmp/a/b/c
Processing: /tmp/a/b
Processing: /tmp/a
Found at: /tmp/a/build.xml, running command...
hello
/tmp/a/b/c/d$ rm /tmp/a/build.xml 
/tmp/a/b/c/d$ r/tmp/mkt.sh cat build.xml
Current directory: /tmp/a/b/c/d
Processing: /tmp/a/b/c/d
Processing: /tmp/a/b/c
Processing: /tmp/a/b
Processing: /tmp/a
Processing: /tmp
build.xml not found.

此外,一旦脚本完成并且控制权返回到用户,我希望当前目录是脚本最初所在的目录

在 bash 中无需执行此操作。子脚本无法更改父 bash 进程的当前密码。尝试以下操作:

$ cd /tmp
$ echo "cd /usr" > a.sh
$ chmod u+x a.sh
$ pwd
/tmp
$ cat a.sh
cd /usr
$ ./a.sh
$ pwd
/tmp

如您所见,尽管脚本cd /usr内部发生了变化,但当前 pwd 并未改变。

相关内容