簡體   English   中英

Bash腳本作為.command不能正確執行

[英]Bash script as .command not executing properly

我有一個簡單的腳本/命令:

當我從shell運行它時:

 txt=testfile
 find ~/Desktop/Rory/Test -type f -exec grep $txt {} \; -exec mkdir $txt \; 

結果是:

Binary file ./TEST.zip matches
and it makes a new directory named testfile

當我將其另存為.command時:

echo "cd: \c"
read dir
echo "txt: \c"
read str
find $dir -type f -exec grep $str {} \; -exec mkdir $str \;

chmod 755並雙擊它,我得到:

Last login: Wed Apr  2 20:44:14 on ttys004
zipher:~ Rory$ /Users/Rory/Desktop/CD.command ; exit;
cd: \c
/Users/Rory/Desktop/Test
txt: \c
txt

然后,它進入手提籃下地獄 ,遞歸地進入另一個命令永遠都不會冒險的地方-我必須^ C它,因為它已經變得很笨拙了。 它不會創建新的目錄或者..哪里我擰狗

我沒有具體的解釋,但有幾點建議:

  • 您的腳本是否有bash shebang行(文件#!/usr/bin/env bash的第一行)? 我看到沒有它,OSX的行為就很奇怪。

  • 我認為提示字符串中的\\c表示禁止尾隨換行符-在bash默認情況下不起作用-您需要使用-e調用echo ,或者-最好-僅使用printf例如, printf "cd: "

  • 我建議您在find命令中對變量引用加雙引號 ,這樣,如果輸入的路徑或字符串包含嵌入式空格或其他字符,該命令就不會中斷。 對外殼具有特殊意義。

到目前為止,我們得到:

printf "cd: "
read dir
printf "txt: "
read str
find "$dir" -type f -exec grep -l "$str" {} \; -exec mkdir "$str" \;

還有更多:

  • 注意, find處理指定目錄的整個子樹 如果只想匹配當前目錄中的文件,請添加-maxdepth 1

  • 請注意, -exec當前目錄中執行命令,而不管在哪里找到匹配文件-如果要在輸入目錄中創建所有目錄,請使用-exec mkdir "$dir/$str" \\; 相反,如果要創建在找到每個匹配文件的子目錄中創建的目錄,請使用-execdir mkdir "$str" \\;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM