-1

Problem is:

grep the output of ps aux for any instance of firefox, if firefox is already running, open link in new tab, if firefox is not running, start firefox and open the link.

Point to be noted here is that I have mentioned the count variable to be greater than 1 because ps aux | grep firefox itself is a process that would be listed, so any other instance other than that. When I run the following script it, goes into loop, what's the right logic?

#!/bin/bash
count=0
while [[ $(ps aux | grep firefox) ]]
do
    count=$((count+1)) ;
    if ( count -gt 1 )
        then    
            nohup firefox --new-tab "mega.nz" &
        else
            nohup firefox "mega.nz" &
    fi
done

Edit : Thanks to the comments and answer below, they helped me get rid of the while loop totally by using pgrep as thrig and Deathgrip mentioned below, but how do I achieve this by while loop or let me know if this cannot be performed with while loop.

3
  • 1
    pgrep can profitably replace ps ... | grep ...
    – thrig
    Jul 5, 2017 at 19:06
  • You are not breaking out of the loop anywhere. Merely checking for a running firefox process, incrementing count, and either running a new firefox (first iteration), or opening a new tab (remaining iterations). Perhaps describe what you want to happen?
    – Deathgrip
    Jul 5, 2017 at 19:30
  • @Deathgrip Do ps aux | grep --firefox, now from the output, if firefox exists in more than 1 processes (2 or more lines on terminal), run the if loop and exit out of while loop Jul 5, 2017 at 19:33

1 Answer 1

1

Why don't you just want something like:

#!/bin/bash
count=0
if [[ $(pgrep firefox) ]]
then    
    nohup firefox --new-tab "mega.nz" &>/dev/null &
else
    nohup firefox "mega.nz" &>/dev/null &
fi

Your script edited, still not sure under what conditions you want to break out of the loop:

#!/bin/bash
count=0
while [[ $(ps aux | grep firefox) ]]
do
    count=$((count+1)) ;
    if [ $count -gt 1 ]
        then    
            nohup firefox --new-tab "mega.nz" &
            break
        else
            nohup firefox "mega.nz" &
    fi
done
2
  • Yes, learned this from the comments above, but am curious to know how to perform this with while loop instead or have someone explain if this cannot be performed by while loop Jul 5, 2017 at 19:45
  • Okay, understood.. No, there is nothing important in while loop here, I understand but wanted to know how to do this the other way round. Thanks. I didn't know break exists in bash also. I have been coding in bash since last 2 weeks or so only. I am a new to linux. Jul 5, 2017 at 20:04

Not the answer you're looking for? Browse other questions tagged .