使用子字符串条件进行Bash while循环

时间:2015-02-01 15:57:20

标签: linux bash shell unix

我有一个while loop的函数应该运行,直到其中一个字符串将是我的第二个字符串的子字符串。 问题是,while循环是无限的,我仔细检查了我的情况,它不应该进入while loop我已经输入的参数。 这是我的两个功能:

## check if the client exist
## if exists return 1 else return 0
function isClientExist () {
        clientToCheck=irabinowitz_tlv-cc-lx64_806
        checkClient=$(p4 client -o -t $clientToCheck 2>&1)
        tempStr="doesn\'t exist"
        if [[ $checkClient != *"$tempStr"* ]]; then
                echo The client exist
                flag=1
        else
                echo the client doesnt exist
                clientToCreate=$clientToCheck
                flag=0
        fi
        return $flag
}
## Fixing the client name by appeding  _number to the client name
function fixClientName () {
        echo fixing the client name...
        numToAppend=1
        tempClientToCheck=$clientToCheck
        echo the temp client to check is: $tempClientToCheck
        clientToCheck+=_$numToAppend
        echo  the client to check is: $clientToCheck
        echo try number $numToAppend
        sleep 20
        while [[ $checkClient != *"$tempStr"* ]]; do

        #       let "numToAppend+1"
                ((++numToAppend))
                clientToCheck=$tempClientToCheck
                echo the client to check in the loop before appending  is: $clientToCheck
                clientToCheck+=_$numToAppend
                echo the client to check in the loop after appending is: $clientToCheck
                echo try number $numToAppend
                sleep 20

        done
        clientToCreate=$clientToCheck
        echo the client to create is $clientToCreate
}

#main
isClientExist
if [ $? -eq 1 ]; then
        fixClientName
fi

1 个答案:

答案 0 :(得分:1)

你不应该反斜杠 - 逃避'

tempStr="doesn\'t exist"

这永远不会匹配您期望的字符串,因此[[ $checkClient != *"$tempStr"* ]];将始终成功。

它不会匹配,因为在双引号字符串中,\'字面意思是 \ ' 。所以反斜杠必须在消息中才能使匹配成功。

使用以下其中一项:

tempStr="doesn't exist"
tempStr=doesn\'t\ exist