Bash while 带子字符串条件的循环

Bash while loop with substring condition

我有一个带有 while loop 的函数,它应该 运行 直到其中一个字符串成为我的第二个字符串的子字符串。 问题是 while 循环是无限的,我仔细检查了我的条件,它不应该进入 while loop 和我输入的参数。 这是我的 2 个函数:

## 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

您不应该反斜杠转义 ' in:

tempStr="doesn\'t exist"

那永远不会匹配您期望的字符串,所以 [[ $checkClient != *"$tempStr"* ]]; 总是会成功。

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

使用以下之一:

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