-1

I can't figure out the bash syntax of a while statement with two conditions where one of them is a function call which returns a number.

I removed all [ ( in this example - but I think I tried them all :)

func() {
    return 12
}

ATTEMPTS=0
MAXATTEMPTS=2

while func -gt 0 && $ATTEMPTS -lt $MAXATTEMPTS 
do
  echo "Hello"
  ATTEMPTS=$((ATTEMPTS+1))
done
Anders
  • 567
  • 1
  • 7
  • 23

2 Answers2

2

Change return to echo and use $(func) (and bring back the brackets so you don't get -gt: command not found:

#!/bin/bash
func() {
  echo 12
}

ATTEMPTS=0
MAXATTEMPTS=2

while [[ $(func) -gt 0 ]] && [[ $ATTEMPTS -lt $MAXATTEMPTS ]]
do
  echo "Hello"
  ATTEMPTS=$((ATTEMPTS+1))
done
Zac Anger
  • 6,983
  • 2
  • 15
  • 42
0

To make it easier to debug, I would often run the condition by itself in the shell and inspect the results. This works because a condition is just a normal bash statement with an exit code. In this case:

$ func() { \
    return 12 \
}
$ func -gt 0 && $ATTEMPTS -lt $MAXATTEMPTS 
$ echo $?
12

This hopefully makes it obvious you're just calling the function with arguments that it ignores (you can show this by calling echo "$@" in the function).

To make it work like you probably want, you need to separate statements.

But it also seems like you got caught up in the way bash uses return which is not like most programming languages, see https://stackoverflow.com/a/17336953/2447844 for explanation and a better solution. Basically, you want to use echo instead of return in the function.

But if you really can't change the func function, I suggest you instead do the following:

func
FUNC_VALUE=$?
while [ $FUNC_VALUE -gt 0 ] && [ $ATTEMPTS -lt $MAXATTEMPS ]
...
blazee
  • 168
  • 1
  • 8