0

I'm struggling with syntax of do while loop with 2 conditions inside the while statement:

while [[ supervisorctl status | grep $1 | awk '{print $2}' != 'RUNNING' ]] && [[ $count -gt 0 ]]; do
       supervisorctl start $1
       sleep 3
       $count=$count -1
done

when i run bash -n on my script to check for syntax error i get the following output:

line 31: conditional binary operator expected
line 31: syntax error near `status'
line 31: `        while [[ supervisorctl status | grep $1 | awk '{print $2}' != 'RUNNING' ]] && [[ $count -gt 0 ]]; do'

can someone please help me figure the correct syntax?

thechmodmaster
  • 709
  • 2
  • 7
  • 18
  • 1
    http://shellcheck.net/ is a good place to start. Short answer: You shouldn't use `[[ ]]` here at all. – Charles Duffy Mar 25 '20 at 17:56
  • Well, not unless your goal is to test for output from the pipeline, in which case it should be `[[ $(...pipeline...) ]]`. But it's better practice to design your pipeline so the last component of it has a true or false exit status so you don't need to inspect output at all. – Charles Duffy Mar 25 '20 at 17:57
  • Consider `supervisorctl status | awk -v service="$1" 'BEGIN { retval=0 }; $1 == service && $2 == "RUNNING" { retval=1 } END { exit retval }'` as such a condition you could use, to not even need `grep` either. – Charles Duffy Mar 25 '20 at 18:02
  • Hi, thanks for your answer. i didn't really got you... However, if for example i just want to check this statement inside the while: `supervisorctl status | grep $1 | awk '{print $2}' != 'RUNNING' `? even this returns an error: `while [[ supervisorctl status | grep $1 | awk '{print $2}' != 'RUNNING' ]]; do supervisorctl start $1 sleep 3 $count=$count -1 done` – thechmodmaster Mar 25 '20 at 18:37
  • Once again, **do not use `[[`** here. – Charles Duffy Mar 25 '20 at 19:20
  • 1
    `while (( count )) && supervisorctl status | awk -v service="$1" 'BEGIN { retval=0 }; $1 == service && $2 == "RUNNING" { retval=1 } END { exit retval }'; do supervisorctl start "$1"; sleep 3; count=$(( count - 1 )); done` – Charles Duffy Mar 25 '20 at 19:22
  • Or, if you really insist on sticking with your old pipeline: `while [[ $(supervisorctl status | grep $1 | awk '{print $2}' != 'RUNNING') ]] && (( count )); do ...` – Charles Duffy Mar 25 '20 at 19:22
  • Thanks again, it works. can you please explain a bit what you did here? `BEGIN { retval=0 }; $1 == service && $2 == "RUNNING" { retval=1 } END { exit retval }` I'm still a beginner in bash and want to understand – thechmodmaster Mar 26 '20 at 11:41

0 Answers0