从 shell 脚本启动 Web 浏览器的干净方法? [英] Clean way to launch the web browser from shell script?
本文介绍了从 shell 脚本启动 Web 浏览器的干净方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 bash 脚本中,我需要启动用户 Web 浏览器.似乎有很多方法可以做到这一点:
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
在 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
是标准化的,应该在大多数发行版中可用.
xdg-open
is standardized and should be available in most distributions.
否则:
eval
是邪恶的,不要使用它.- 引用你的变量.
- 以正确的方式使用正确的测试运算符.
eval
is evil, don't use it.- Quote your variables.
- Use the correct test operators in the correct way.
这是一个例子:
#!/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"
这篇关于从 shell 脚本启动 Web 浏览器的干净方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文