The Vivandiere
The Vivandiere

Reputation: 3191

Shell script, stop running if failed

I have a shell script that runs a test repeatedly :

#!/bin/tcsh                                                                                                   
set x = 1                                                                                                     
while ($x <= 10000)                                                                                           
    echo $x                                                                                                   
    ./test                                                                  
    @ x += 1                                                                                                  
end 

I am trying to adapt it to break the loop and stop running if the test failed, i.e. the test executable returned with a non-zero status. I thought the following change would work.

#!/bin/tcsh                                                                                                   
set x = 1 
set y = 0                                                                                                    
while ($x <= 10000 && $y == 0)                                                                                           
  echo $x                                                                                                   
  @ y = ./test                                                                  
  @ x += 1                                                                                                  
end 

But, I get error @: Expression syntax

Can you please tell me what did I do wrong, and how to capture the return value of ./test in a variable so I can break the loop, or some other way to break the loop upon encountering the test failure

Upvotes: 0

Views: 489

Answers (1)

William Pursell
William Pursell

Reputation: 212504

I'm not a fan of scripting in csh, and I highly advise against it. However, in this case, csh seems to do the right thing, and you can simply do:

#!/bin/tcsh                                                                                                   
set x = 1                                                                                                     
while ($x <= 10000)                                                                                           
    echo $x                                                                                                   
    ./test || break                                                             
    @ x += 1                                                                                                  
end 

Upvotes: 2

Related Questions