一次做两个过程。 1)找到命令2)if-else条件取决于命令行参数,它根本不进入elif条件。为什么?

时间:2016-04-08 06:48:43

标签: bash shell

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条件,但进入其他部分。为什么呢?

1 个答案:

答案 0 :(得分: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)然后分配变量:

par1=$1
count=$2

2)要验证字符串,您必须使用==,即[[ "${par1}" == "arg2" ]]

3)验证号码"不需要[[ $count -eq 0 ]]

4)正如您所看到的,我已经使用了find . -name "test*",并且我创建了两个目录test1 test2

输出:

[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作为查找命令的结果

#!/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
相关问题