2015-03-25 117 views
0

find命令是:在linux的bash shell查找命令

find ./ \(-path dir_a -o -path dir_b \) -prune 

我要轉換爲:

./find.sh dir_a dir_b 

所以我的代碼(在不工作):

function myfind() { 
    num=1 
    tmp="" 
    for i in [email protected] 
    do 
     tmp="$tmp -path './$i' " 
     if [ $((num++)) -ne $# ] 
     then 
      tmp="${tmp} -o" 
     fi 
    done 
    echo $tmp # this is ok!! 
    find ./ \($tmp \) -prune # is doesn't work, why??? 
} 
+1

請勿使用單個變量'tmp'請改用[array](http://mywiki.wooledge.org/BashGuide/Arrays)。在[此鏈接]中檢查'quoting'中的最後一個代碼片段(http://mywiki.wooledge.org/BashGuide/Practices#Quoting) – anishsane 2015-03-25 06:46:57

+0

您使用'$ @'未加引號顯然是錯誤的。它需要用雙引號引起其特殊含義,與'$ *'(引用或不引用)不同。 – tripleee 2015-03-25 06:52:33

回答

1

因爲您需要腳本與導演一起正常工作,所以您試圖在「經典sh」的一般情況下無法解決名稱爲*'"[ ]"',而普通的舊扁字符串根本不允許正確引用(容易,或者即使具有相當大的複雜性)。幸運的是,如評論中所建議的那樣,Bash數組允許您在所有必要的控制級別下執行此操作。只要確保始終在可能包含文件名的任何東西周圍使用引號。

#!/bin/bash 
dir_args=() 
oh= 
for i; do 
    dir_args+=($oh '-path' "$i") 
    oh='-o' 
done 
find . \("${dir_args[@]}" \) -prune 
+2

在POSIX shell中執行它並不困難:'''$#「-eq 0]&& exit; i = $#;設置 - 「$ @」-false; while [「$ i」-gt 0];做s = $ 1;轉移;設置 - 「$ @」-o -path「$ s」; I = $(第(i-1));完成;找 。 \(「$ @」\)-prune'。 – 2015-03-25 08:40:12

+0

@gniourf_gniourf嘿,你應該發佈這個答案。 – tripleee 2015-03-25 08:42:25

+0

不......沒有什麼和你的答案在概念上有什麼不同(這是正確的答案,我提高了)。你可以將它包含在你的內容中,或者留作評論以備將來參考。 – 2015-03-25 08:44:12