How do I open an URL from a bash script?
Solution 1
xdg-open
is actually a shell script (on my system). It uses heuristics to guess what your browser is. You could see what it is trying to do by running it with from within the script with
sh -x xdg-open http://localhost:9000/ >&/tmp/errors
Look in /tmp/errors
for any failure messages.
You may also simply replace xdg-open by the name of your browser, eg firefox.
If you are launching a script from a desktop button, it may be that when the launcher gets to the end of the script, it kills the process group. Try adding a
sleep 99999
at the end to see if this is the case.
If you are trying to run your startserver.sh
from somewhere other than your desktop environment, xdg-open
may have a hard time trying to find which browser to use. You could try setting some environment variables to help it.
Solution 2
It's a very short answer, start node server.js
as background process:
#!/bin/bash
node server.js &
xdg-open http://localhost:9000/
Related videos on Youtube
Wouter
Updated on September 18, 2022Comments
-
Wouter over 1 year
I have a simple script to start a node.js webserver and open the URL in a browser. However the last part doesn't seem to work, it wont open the URL in a browser (or anywhere else).
This is the code I got so far:
#!/bin/bash node server.js; xdg-open http://localhost:9000/;
Everywhere I search I find the same, I have to use:
xdg-open URL
but it only seems to work while typing that in the terminal, not in my startserver.sh file. It will start the server but not open the URL, typing the code in a terminal however does seem to work.
It's confusing, why doesn't it work inside my script?
-
muru over 9 yearsHow are you running the script?
-
steeldriver over 9 yearsIt may just be a timing issue (attempting to open the URL before the server has fully started) - try adding a
sleep 2
orsleep 5
between the two commands. -
Wouter over 9 yearsI tried with sleep but I still have the same problem. How I run the script? I configured it so that I double-click the file it will ask me what to do, then I 'Run it in terminal'. I do want a terminal window to open and stay open as long as the server is running, which is not a problem. I tried just the xdg-open without starting the node server, also with other urls but it simply doesn't work.
-
s3lph over 9 yearsIf xdg-open really doesn't work (which would surprise me), try
x-www-browser URL
. This will open the URL in the default browser -
j0h about 9 yearsIs opening it in firefox acceptable? How about thought nautilus or caja?
-