Clean way to launch the web browser from shell script?

前端 未结 6 1622
独厮守ぢ
独厮守ぢ 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:16

    Taking the other answers and making a version that works for all major OS's as well as checking to ensure that a URL is passed in as a run-time variable:

    #!/bin/bash
    if [ -z $1 ]; then
      echo "Must run command with the url you want to visit."
      exit 1
    else
      URL=$1
    fi
    [[ -x $BROWSER ]] && exec "$BROWSER" "$URL"
    path=$(which xdg-open || which gnome-open) && exec "$path" "$URL"
    if open -Ra "safari" ; then
      echo "VERIFIED: 'Safari' is installed, opening browser..."
      open -a safari "$URL"
    else
      echo "Can't find any browser"
    fi
    

提交回复
热议问题