2016-04-08 19 views
-1
find . -type d -exec sh -c '(cd {} && 
count=$2 

if [[ "$count" -eq 0 ]] ;then 

    echo "there are 0 .mov files in this path" 

elif [[ "$count" -eq 1 ]] ;then 

    echo "there is 1 .mov file in this path" 

elif [[ $1 = "arg1" ]] ; then 

    echo "arg1 " 

elif [[ "$1" == "arg2" ]] || [[ "$1" == "arg10" ]] ; then 

    echo "arg2 or arg10 " 

else 

echo "else" 

fi 

#)' ';' 

我想輸入所有子目錄,並嘗試使用if-else條件來執行一個進程。 如果第一行和最後一行是註釋腳本,則工作正常。否則腳本永遠不會進入arg1 elif條件,或arg2 elif條件但進入else部分。爲什麼?一次執行2個進程。 1)根據命令行參數找到命令2)if-else條件,它根本不會進入elif條件。爲什麼?

+0

引用的shell命令如何獲得它的'$ 2'? –

+0

哪些是$ 1和$ 2的價值?我認爲$ 1應該是查找結果的值 – ClaudioM

+0

直接的問題是,您正在使用Bash結構,例如'[['在腳本代碼片段中將您傳遞給'sh'。但是,您希望腳本實際完成的內容非常不清楚,並且您沒有對要求澄清的問題做出迴應。投票結束不清楚。 – tripleee

回答

0

這個工程:

#!/bin/bash 


find . -name "test*" -type d -exec bash -c '(cd {} && 
par1=$1 
count=$2 
echo "count [$count] - par1[$par1]" 

if [[ $count -eq 0 ]];then 

    echo "there are 0 .mov files in this path" 

elif [[ $count -eq 1 ]];then 

    echo "there is 1 .mov file in this path" 

elif [[ "${par1}" == "arg1" ]];then 

    echo "arg1" 

elif [[ "${par1}" == "arg2" ]] || [[ "$1" == "arg10" ]];then 

    echo "arg2 or arg10 " 

else 

echo "else" 

fi 

)' bash $1 $2 {} \; 

試圖解釋:

1)假設$1$2是外部參數,它們必須被傳遞到要分配如此前的腳本,在腳本的末尾添加:

bash $1 $2 {} \;

2)然後分配變量:

2)驗證字符串必須使用==[[ "${par1}" == "arg2" ]]

3)以驗證號碼"不需要[[ $count -eq 0 ]]

4)你可以看到我用find . -name "test*"和我ve創建了兩個目錄test1test2

輸出:

[myShell] ➤ ./i arg1 0 
count [0] - par1[arg1] 
there are 0 .mov files in this path 
count [0] - par1[arg1] 
there are 0 .mov files in this path 

[myShell] ➤ ./i arg1 1 
count [1] - par1[arg1] 
there is 1 .mov file in this path 
count [1] - par1[arg1] 
there is 1 .mov file in this path 


[myShell] ➤ ./i arg1 2 
count [2] - par1[arg1] 
arg1 
count [2] - par1[arg1] 
arg1 

[myShell ➤ ./i arg2 2 
count [2] - par1[arg2] 
arg2 or arg10 
count [2] - par1[arg2] 
arg2 or arg10 

相反,如果你不需要使用輸入作爲放慢參數,但內部變量,你可以像這樣做並使用$ 3中find命令的結果

#!/bin/bash 

var1=arg1 
var2=2 

find . -name "test*" -type d -exec bash -c '(cd {} && 
par1=$1 
count=$2 
echo "count [$count] - par1[$par1] - directory[$3]" 

if [[ $count -eq 0 ]];then 

    echo "there are 0 .mov files in this path" 

elif [[ $count -eq 1 ]];then 

    echo "there is 1 .mov file in this path" 

elif [[ "${par1}" == "arg1" ]];then 

    echo "arg1" 

elif [[ "${par1}" == "arg2" ]] || [[ "$1" == "arg10" ]];then 

    echo "arg2 or arg10 " 

else 

echo "else" 

fi 

)' bash $var1 $var2 {} \; 

輸出

[myShell] ➤ ./i 
count [2] - par1[arg1] - directory[./test1] 
arg1 
count [2] - par1[arg1] - directory[./test2] 
arg1 
+0

「sh -c」中的子shell沒用,你應該雙引號文件名變量和用戶提供的變量。 – tripleee

+0

謝謝你的回答 – amit