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

标签 linux bash shell unix

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

最佳答案

你不应该对 ' 进行反斜杠转义:

tempStr="doesn\'t exist"

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

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

使用以下之一:

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

关于linux - 带有子字符串条件的 Bash while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28264636/

相关文章:

bash - GNU Screen - 在 shell 或脚本的后台运行命令中创建 screen

c - bash -i >&/dev/tcp/127.0.0.1/1234 0>&1

javascript - linux php 执行() msg​​get :Permission Denied

c - 如何搜索有gid的群组?

phpmyadmin登录页面问题

linux - 为性能标准编写 bash 代码

linux - 在linux中抑制JQ​​解析错误信息

bash - 通过 dpkg-query 安装缺失包的脚本

linux - 在 Linux 中使用 shell 脚本监控日志和发送警报邮件

linux - android studio avd 中的模拟器在 Pop 中非常慢! _os