bbmhmmad
bbmhmmad

Reputation: 392

Why is this one line until loop not behaving as expected?

I have this one line shell script where I am attempting to continuously connect to my Redis server until connection is established (outputs 'OK' on success). However, I must be doing something wrong as the script seemingly does...nothing.

bash-5.0# sh -c "until [ $response=="OK" ]; do response="$((printf "AUTH <redis pw>\r\n") | nc -w5 <redis IP> <redis port>)"; echo $response; done;"
bash-5.0#

What am I doing wrong?

Upvotes: 0

Views: 171

Answers (1)

ghoti
ghoti

Reputation: 46856

First off, don't assume that sh and bash are the same. In most places they are not, and even bash will behave differently when invoked as sh.

At the moment, your until condition always evaluates as true because the expression is considered merely a non-null string. To demonstrate:

$ [ ==OK ] && echo yo
yo

Remember that [ is an alias for /bin/test. You can man test for documentation, but the short answer is, use a single equals, and spaces around everything. Oh, and quote the variables, not the special-character-free constants.

In addition, mind your quotes. You start a double quoted string before until, and then end it before OK. If you want to embed double quotes within double quotes, you need to escape them. But it's even better/clearer if you can avoid them.

Perhaps this:

# bash -c 'until [[ "$response" = OK ]]; do response="$(printf "AUTH %s\r\n" "$redis_pw" | nc -w5 <redis IP> <redis port> )"; echo "$response"; done'

Or if you prefer to be POSIXy and not depend on bash:

# sh -c 'until [ "$response" = OK ]; do response="$(printf "AUTH %s\r\n" "$redis_pw" | nc -w5 <redis IP> <redis port>)"; echo "$response"; done'

Upvotes: 2

Related Questions