how to check if the result of a bash function is a specific string in while loop?

Viewed 40

(I'm not a linux guy) and I want to check the status of a service when its updating (takes about 10 minutes) to make sure it is successful. I use a function to run the status command and while loop as follow:

get_status() { echo ...my command runs here and return the statue; }

I simply can get the status like $(get_status). Now I want to see what is the status and take action:

while $(get_status) == "PENDING"; do echo retrying... && sleep 5; done

I've tried different ways like single/double brackets but cannot get the while comparison to work properly? Can anybody help please?

1 Answers

The while loop doesn't know anything about comparison tests. It only knows how to check the exit status of a command, and $(get_status) == "PENDING" is not a command. The brackets you want are for either a test command or a bash conditional expression command.

while test "$(get_status)" = "PENDING"; do

or

# [ is a synonym for test, with the added requirement that
# there be a final argument ] to complete the illusion of
# syntax.
while [ "$(get_status) = "PENDING" ]; do

or

while [[ $(get_status) == "PENDING" ]]; do

In the first two cases, = is preferred as the correct equality operator for test/[. In the last case, == may be used, and the quotes can be dropped around $(get_status) because no word-splitting or filename generation is performed on expansions in [[ ... ]]. (The quotes could be dropped around the literal word PENDING in all three cases, but could remain necessary for some right-hand arguments inside [[ ... ]] for reasons beyond the scope of this question.)

Related