![彈出當前目錄直到找到特定文件](https://rvso.com/image/1311342/%E5%BD%88%E5%87%BA%E7%95%B6%E5%89%8D%E7%9B%AE%E9%8C%84%E7%9B%B4%E5%88%B0%E6%89%BE%E5%88%B0%E7%89%B9%E5%AE%9A%E6%96%87%E4%BB%B6.png)
我有興趣編寫具有以下行為的腳本:
- 查看目前目錄中是否存在 build.xml 文件,如果存在,請執行透過腳本參數提供的命令。
- 如果沒有,則彈出目前目錄並查看父目錄。轉到1。
一旦我們找到檔案或到達根目錄,腳本就會結束。另外,一旦腳本完成並且控制權返回給用戶,我希望當前目錄是腳本最初所在的目錄
我對 shell 腳本編寫不太熟悉,但任何幫助/指導將不勝感激。
答案1
在 bash 中,您可以像這樣實現這一點:
mkt.sh
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 進程的目前 pwd。嘗試這個:
$ 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
在其中發生了變化。