Home > database >  Bash: while loop to print message as long as command runs
Bash: while loop to print message as long as command runs

Time:09-23

A while ago, we upgraded to the latest version of Laravel Mix. This has a much more visual output when running commands like yarn mix --production, but it creates an issue for us on tools like Forge and Ploi, since the progress bar is not seen by these tools, and our deployment return an error, since Forge and Ploi think that the command is stuck, as it runs for 5 - 15 minutes due to the huge amount of code it needs to compile.

While we are working on optimizing our code to reduce compilation time, I am looking for a way to get the current code compiled in Forge or Ploi. I came up with the following idea:

If the progress bar is not seen, maybe I can echo a line of text as long as the command runs, which hopefully will prevent the timeout. To achieve this, I created the following script:

COUNTER=0;
while yarn mix --production &> /dev/null;
do
  echo "Running for" $COUNTER "seconds";
  sleep 10;
  let "COUNTER  = 10";
done

... but this doesn't seem to do the trick as nothing is printed after 10 seconds. I'm a noob with bash, so maybe someone can help me point out what I'm doing wrong?

PS: I'm doing &> /dev/null to avoid having both the counter and the progress bar, as the --no-progress flag doesn't seem to do that.

CodePudding user response:

Well, you need to run your command in the background if you want to be able to do something else while it runs. Otherwise, while condition will be evaluated only when yarn is finished

You need something like :

yarn mix --production < /dev/null 1> /dev/null &
pid=$!
COUNTER=0;
while kill -0 $pid &> /dev/null
do
  echo "Running for" $COUNTER "seconds";
  sleep 10;
  let "COUNTER  = 10";
done

Edit: replaced jobs -p | grep -q $pid by kill -0 $pid &> /dev/null after Jetchisel's comment. It's better than piping the output of jobs and feeding it to a grep subprocess...

  • Related