明确地说,Ignacio 是正确的here,因为不应直接执行 .desktop 文件。这是可能的(正如您所发现的),但不明智。
另外注意,不要使用xdg-open。如果有正确关联的 mime 类型,它可能会碰巧起作用,但这并不可靠。
您应该使用gtk-launch。用法如下:
gtk-launch APPLICATION [URI...]
gtk-launch app-name.desktop
gtk-launch app-name
这里是 man 条目:
名字
gtk-launch - Launch an application
概要
gtk-launch [APPLICATION] [URI...]
描述
gtk-launch launches an application using the given name. The
application is started with proper startup notification on a default
display, unless specified otherwise.
gtk-launch takes at least one argument, the name of the application to
launch. The name should match application desktop file name, as
residing in /usr/share/application, with or without the '.desktop'
suffix.
If called with more than one argument, the rest of them besides the
application name are considered URI locations and are passed as
arguments to the launched application.
请注意gtk-launch 需要安装.desktop 文件(即位于/usr/share/applications 或$HOME/.local /share/applications)。
所以为了解决这个问题,我们可以使用一个 hackish 的小 bash 函数,在启动它之前临时安装所需的 .desktop 文件。安装 .desktop 文件的“正确”方法是通过desktop-file-install,但我将忽略它。
launch(){
(
# where you want to install the launcher to
appdir=$HOME/.local/share/applications
# the template used to install the launcher
template=launcher-XXXXXX.desktop
# ensure $1 has a .desktop extension, exists, is a normal file, is readable, has nonzero size
# optionally use desktop-file-validate for stricter checking
# if ! desktop-file-validate "$1" 2>/dev/null; then
if [[ ! ( $1 = *.desktop && -f $1 && -r $1 && -s $1 ) ]]; then
echo "ERROR: you have not supplied valid .desktop file" >&2
exit 1
fi
# ensure the temporary launcher is deleted upon exit
trap 'rm "$launcherfile" 2>/dev/null' EXIT
launcherfile=$(mktemp -p "$appdir" "$template")
launchername=${launcherfile##*/}
if cp "$1" "$launcherfile" 2>/dev/null; then
gtk-launch "$launchername" "${@:2}"
else
echo "ERROR: failed to copy launcher to applications directory" >&2
exit 1
fi
exit 0
)
}
您可以像这样使用它(如果需要,还可以传递其他参数或 URI):
launch ./path/to/shortcut.desktop
另外,我写了一个答案here,概述了启动 .desktop 文件的所有方法。它提供了gtk-launch 的一些替代方案,可能会有所帮助。