首页 > 解决方案 > Bash脚本将字符串与 : 进行比较

问题描述

在比较字符串中带有 ':' 时遇到问题!

该脚本是 macOS 上的 bash。

我拥有的字符串来自调用输出的 grepdocker-compose ps和 is (health: starting)

我已经尝试过if [[ $health == '(health: starting)' ]];then和变种。为了测试我已经回显的值并得到(health:我试图在一个小脚本中重现这个问题,但它似乎工作正常。

此脚本正在进行中,因此可能存在其他问题

function getStatus {
    local  __resultvar=$1
    local  myresult='some value'

#   call=$(docker-compose --compatibility ps | grep "^$1 ")
#   a=( $call )

#   asize=${#a[@]}


    case $asize in
    4)
        status=${a[2]}
    ;;
    6)
        status=${a[4]}
    ;;
    7)
        status=${a[5]}
        if [[ "$status" =~ [^A-Za-z] ]]; then
            status=${a[4]}
        fi
    ;;
    8)
        status=${a[6]}
    ;;
    9)
        status=${a[4]}
    ;;
    10)
        service=${a[0]}
        if [[ $service == "identification-service" ]]; then
            status=${a[7]}
        else
            status=${a[4]}
        fi
    ;;
    11)
        status=${a[8]}
        if [[ $status -eq "Up" ]]; then
            health=${a[9]}
        else
            health=""
        fi
    ;;
    12)
        status=${a[8]}
        if [[ $status -eq "Up" ]]; then
            health="${a[9]}"
        else
            health=""
        fi
    ;;
    13)
        status=${a[8]}
        if [[ $status -eq "Up" ]]; then
            health="${a[9]}"
        else
            health=""
        fi
    ;;
    *)
        echo "Cant decode that! $asize elements"
        echo
        index=0
        while [ $index -le $asize ]
        do
            echo "${a[$index]}"
            ((index++))
        done
        exit
    ;;
    esac

    if [[ "$health" ]]; then
        if [[ $health == '(healthy)' ]];then
            result='healthy'
        elif [[ $health == '(unhealthy)' ]];then
            result='unhealthy'
        elif [[ $health == '(health: starting)' ]];then
            result='starting'
        else
            result=$health
        fi
    else
        result=$status
    fi
}

call=$(docker-compose --compatibility ps | grep "^$1 ")
# echo "$call"
a=( $call )

asize=${#a[@]}
# echo "Size: $asize - '$call'"

result=""
for VARIABLE in {1..10}
do
    getStatus
    echo "result = $result"
    if [[ $result == 'Up' ]]; then
        echo "$1 is up"
        exit
    elif [[ $result == 'healthy' ]]; then
        echo "$1 is up and healthy"
        exit
    fi
    echo "currently $result - waiting 3 second before checking again"
    sleep 3
done

echo "status of $1 is: $status but $health"
echo

标签: bashmacosdocker

解决方案


这个方法使用怎么样case/esac

  case $health in
  (*:*) echo has a colon;;
  (*)   echo has no colon;;
  esac

这很容易扩展到您的其他测试(healthy)等。


推荐阅读