我有一个带有 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/