2

/root/file has

https://stackoverflow.com
https://stackexchange.com
https://reddit.com

I need to open all these websites one after another in one firefox window only. Here is my code

#!/bin/bash
while read line
do 
    if pgrep firefox; 
    then 
        firefox --new-tab "$line" ; 
    else 
        firefox "$line" ;
    fi 
done < /root/file

I tried nohup also but it didn't work.

The problem is that if I use ; it would bind to shell process and won't run the next command until I exit out of firefox and if I use nohup or & , it would be separated from the shell and will open the new window of firefox instead of new tab. In both cases, every website opens in new window.


Partially Solved

xdg-open opens websites in one window when commands are manually typed on the shell like

$ xdg-open https://stackoverflow.com
$ xdg-open https://stackexchange.com
$ xdg-open https://reddit.com

but it doesn't work in script. I have the following script with xdg-open

#!/bin/bash
while read line
do 
    xdg-open "$line"
done < /root/file

but it again opens websites in different windows instead single window.

3
  • Can you change the lines to start with http:// or https://? Then, instead of calling firefox you could just open it which will navigate to it with your default browser. I recently discovered (with chrome anyway) if you open site1; open site2; open site3 they will all open in separate tabs in the same window but if you break it into different lines each will open in a new window.
    – jesse_b
    Aug 23, 2017 at 12:56
  • @Jesse_b I did open https://stackexchange.com, it doesn't work. Aug 23, 2017 at 13:00
  • @Jesse_b xdg-open works though Aug 23, 2017 at 13:12

2 Answers 2

3

Your problem here is that it takes some time for Firefox to start. If you run it in the background, next time you do firefox --new-tab, your first instance has not quite started and is not ready to open another tab. You must wait some time after starting the first Firefox instance:

#!/bin/bash
while read line
do
    if pgrep -u $USER firefox > /dev/null
    then
        firefox --new-tab "$line" &
    else
        firefox "$line" &
        sleep 3                 # You may want to tune this value
    fi < /dev/null
done < /root/file

Beware that with this kind of construct any program in your loop may eat what comes from stdin and this will end your loop prematurely. That's why I have preventively added < /dev/null to the if part.

2

You just need to:

firefox https://stackoverflow.com https://stackexchange.com https://reddit.com

According to mozilla's docs

-url URL

Open URL in a new tab or window, depend on the browser option. -url can be omitted. You may list multiple URLs, separated by spaces. Firefox and SeaMonkey only.

So you can write your script as

#!/bin/bash
firefox $(cat /root/file | tr '\n' ' ') &

You must log in to answer this question.

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