Clean way to launch the web browser from shell script?

In a bash script, I need to launch the user web browser. There seems to be many ways of doing this:

  • $BROWSER
  • xdg-open
  • gnome-open on GNOME
  • www-browser
  • x-www-browser
  • ...
  • Is there a more-standard-than-the-others way to do this that would work on most platforms, or should I just go with something like this:

    #/usr/bin/env bash
    
    if [ -n $BROWSER ]; then
      $BROWSER 'http://wwww.google.com'
    elif which xdg-open > /dev/null; then
      xdg-open 'http://wwww.google.com'
    elif which gnome-open > /dev/null; then
      gnome-open 'http://wwww.google.com'
    # elif bla bla bla...
    else
      echo "Could not detect the web browser to use."
    fi
    

    xdg-open is standardized and should be available in most distributions.

    Otherwise:

  • eval is evil, don't use it.
  • Quote your variables.
  • Use the correct test operators in the correct way.
  • Here is an example:

    #!/bin/bash
    if which xdg-open > /dev/null
    then
      xdg-open URL
    elif which gnome-open > /dev/null
    then
      gnome-open URL
    fi
    

    Maybe this version is slightly better (still untested):

    #!/bin/bash
    URL=$1
    [[ -x $BROWSER ]] && exec "$BROWSER" "$URL"
    path=$(which xdg-open || which gnome-open) && exec "$path" "$URL"
    echo "Can't find browser"
    

    python -mwebbrowser http://example.com
    

    在许多平台上工作


    OSX:

    $ open -a /Applications/Safari.app http://www.google.com
    

    or

    $ open -a /Applications/Firefox.app http://www.google.com
    

    or simply...

    $ open some_url
    
    链接地址: http://www.djcxy.com/p/57058.html

    上一篇: 检查Makefile中是否存在程序

    下一篇: 干净的方式从shell脚本启动Web浏览器?