Home > Net >  How to make working while loop in the bash?
How to make working while loop in the bash?

Time:12-22

I`m not really coder. Just need tiny script for myself.

I want a save file of Home bank was copied to google drive every time I close the program. Copy script work fine, but trigger not working.

I want loops to check if program open or been closed. But it not work, and I can`t understand how to do it.

Trigger code below.

#! /bin/bash

cycle=0
open=$(ps -eo cmd | grep homebank)
echo "$open"

while [ $cycle = 0 ]
do
    if [ "$open" = 'homebank grep homebank' ]
    then [ $cycle = 1 ]
    echo 'homebank was opened'
    fi
done
while [ $cycle = 1 ]
do
    if [ "$open" = 'grep homebank' ]
    then
    cycle=0
    bash ~/.scripts/home-bank-updater
    echo 'homebank was closed'
    fi
    done

Thank you very much for you attention and help.

CodePudding user response:

I see a few problems here. First, open=$(ps -eo cmd | grep homebank) sets the open variable to the output of that command as of when it's assigned. The variable never gets updated, so the value will never change and retesting it will just give the same result over and over. To recheck, you need to re-run the command.

But this is a bad way to check anyway. For one thing, the output won't be homebank grep homebank; it might be homebank<newline character>grep homebank or grep homebank<newline character>homebank or possibly something even else. You're much better off using pgrep if it's available, as it's designed to eliminate this sort of problem. If it's not, use ps -eo cmd | grep '[h]omebank' -- the brackets will prevent the grep command from matching itself, so you'll only see the process you're interested in.

And rather than capturing the output from the pgrep/grep command, just use the exit status of the command itself (and use -q or >/dev/null to discard output):

if pgrep homebank >/dev/null; then

or

if ps -eo cmd | grep -q '[h]omebank'; then

Second, then [ $cycle = 1 ] doesn't set the value of cycle, it tests it (and doesn't do anything with the result). You want then cycle=1. Except I'd skip that variable entirely, and just use the pgrep result as the loop test (and add a delay, so it doesn't try to test every microsecond):

until pgrep homebank >/dev/null; do
    sleep 0.5
done
echo 'homebank was opened'

I'm not sure I understand what the second loop is for; is it to wait until the homebank process exits? If so, it's redundant, since the first loop already waited for that so I'd just include those steps inline without the loop.

CodePudding user response:

I suggest with bash:

while true; do
  if pgrep homebank >/dev/null; then
    echo open;
  else
    # bash ~/.scripts/home-bank-updater
    echo closed;
  fi;
  sleep 2
done
  • Related