Clean way to launch the web browser from shell script?

前端 未结 6 1624
独厮守ぢ
独厮守ぢ 2020-12-04 07:58

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

  • $BROWSER
  • xdg-open
  • <
6条回答
  •  死守一世寂寞
    2020-12-04 08:11

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

    Otherwise:

    1. eval is evil, don't use it.
    2. Quote your variables.
    3. 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"
    

提交回复
热议问题