PHP Learner
PHP Learner

Reputation: 741

How to use a command output as for loop condition in bash?

I wrote a for loop to work while a PID is running:

for (( j=0; (j < 40) && `kill -0 $pid` ; j++ )); do
  printf "."
  sleep 1
done

But it does not work and shows following error:

line 98: ((: (j < 40) &&  : syntax error: operand expected (error token is "&&  ")

I tried other options such as:

for (( j=0; (j < 40) && (kill -0 $pid) ; j++ )); do
for (( j=0; ((j < 40)) && ((kill -0 $pid)) ; j++ )); do
for (( j=0; ( ((j < 40)) && ((kill -0 $pid)) ) ; j++ )); do
for (( j=0; [ ((j < 40)) && ((kill -0 $pid)) ] ; j++ )); do
for (( j=0; ((j < 40)) && [kill -0 $pid] ; j++ )); do

But all of above variations cause some errors.

Upvotes: 1

Views: 143

Answers (1)

larsks
larsks

Reputation: 311516

You can't use command substitution with ` inside of the arithmetic evaluation context of ((...)). It is probably easiest to rewrite this as a while loop.

tries=0
while kill -0 $pid; do
  (( tries++ > 40 )) && break
  printf "."
  sleep 1
done

Upvotes: 2

Related Questions