Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash Shell Do While Loop Infinite loop?

Basically this is my code:

bay=$(prog -some flags)
while [ $bay = "Another instance of this program is running, please exit it first" ]
do
echo "Awaiting Access to program"
do
.....

I have program which will only allow one instance to be run at one time due to the way it interacts with my hardware, when another instance is running it kicks out the following message "Another instance of this program is running, please exit it first".

I need to beable to run multiple scripts which will utilise this same program so I've decided to use the above code. My problem is that when I run my two scripts one will gain access to the program and run as desired but the other will notice the error and then get stuck in an infinate loop echoing "Awaiting Access to program".

Have missed some thing? Is the Statement executing the CLI command or just reffering back to its origanal execution? Or is my problem else where?

like image 987
bikerben Avatar asked Dec 22 '22 07:12

bikerben


2 Answers

You are not updating your bay variable inside of the loop somewhere. It gets set once and stays the same. You need to recalculate it every time.

Either set bay within the loop, or in the condition of the while.

while [ `prog -some flags` = "Another instance of this program is running, please exit it first" ]

Edit:

From your comment, you want to be able to reference this output later. You can go back to what you had, but inside of your blocking loop, put your bay=$(prog -some flags) command inside of the loop. It will stick around for you to use later.

bay=$(prog -some flags)
while [ $bay = "Another instance of this program is running, please exit it first" ]
do
echo "Awaiting Access to program"
bay=$(prog -some flags)
done
.....
like image 71
Donald Miner Avatar answered Dec 24 '22 02:12

Donald Miner


More DRY and instead of hammering prog, I'd wait for the user to do something first:

while true
do
  bay=$(prog -some flags)
  case "$bay" in
    "Another instance of this program is running, please exit it first")
      read -p "Awaiting Access to program. Close it and hit enter: " x ;;
    *) break ;;
  esac
done
echo "Results: $bay"
like image 20
glenn jackman Avatar answered Dec 24 '22 00:12

glenn jackman