2015-03-25 114 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