通过运行gio open --help
可以看到该命令gio open
将使用该特定文件类型的默认应用程序打开文件。
我怎样才能获得用于以命令行形式打开该文件的应用程序的输出?
我希望有类似的东西gio open somefile.txt --print-application
,例如输出类似的东西gedit
。
答案1
您不能使用gio
它,但您可以使用它xdg-mime
来查询文件的文件类型,然后使用它来获取默认应用程序的描述文件:
# This prints the mime type of somefile.txt
xdg-mime query filetype somefile.txt
# Output, for example: text/plain
# This queries the default application that opens a mime type
xdg-mime query default text/plain
# Output, for example: gedit.desktop
您可以通过流程替换将这两件事结合起来;或者将它们放入 shell 函数中:
# do a substitution to do this on one line
xdg-mime query default $(xdg-mime query filetype somefile.txt)
# Or make a small function that solves the whole thing:
function get_handler_application() {
filetype="$(xdg-mime query filetype "$1")"
xdg-mime query default "${filetype}"
}
# call like:
# get_handler_application somefile.txt
但事实是你会发现你得到的结果是不是一个可执行文件,而是一个 .desktop 文件 - 这是一个重要功能,因为桌面文件包含程序调用时需要使用的所有选项。
:
您可以在环境变量中每个分隔路径下名为“applications”的目录中找到这些桌面文件$XDG_DATA_DIRS
。
如果你的 shell 是zsh
,处理起来会非常优雅:
#!/usr/bin/zsh
# Copyright 2023 Marcus Müller
# SPDX-License-Identifier: GPL-3.0-or-later
# We can get the name of the file handler this way,
# for example:
# get_handler_application aaargh.txt
# outputs:
# text/plain
function get_handler_application() {
filetype="$(xdg-mime query filetype "$1")"
xdg-mime query default "${filetype}"
}
# Get the full path to the specific file that opens this file
# There's multiple paths, and user-defined ones take priority
# over system-defined ones. For example:
# get_handler_desktop_file aaargh.txt
# outputs:
# pluma.desktop
function get_handler_desktop_file(){
desktop_fname="$(get_handler_application "$1")"
for candidate in ${(ps.:.)XDG_DATA_DIRS}; do
fullpath="${candidate}/applications/${desktop_fname}"
[[ -r "${fullpath}" ]] && printf '%s' ${fullpath} && break
done
}
# Get all the commands that are specified in the desktop file.
# There can be multiple, because some file handlers have extended
# options for opening things, like "open in new window" or "make
# new document from this template.
# For example:
# get_handler_command_lines holygrail.html
# outputs:
# firefox %u
# firefox --new-window %u
# firefox --private-window %u
# firefox --ProfileManager
function get_handler_command_lines() {
sed -n 's/^Exec=\(.*\)*/\1/p' "$(get_handler_desktop_file "$1")"
}
答案2
gio
您只需两步即可完成:
通过以下方式获取内容类型(即 mime 类型)gio info
:
gio info -a standard::content-type clip.mp4
打印出如下内容:
uri: file:///home/tmp/clip.mp4
attributes:
standard::content-type: video/mp4
现在您知道了可以运行的 mime 类型
gio mime video/mp4
它打印该 mime 类型的所有注册处理程序。首先列出默认值:
Default application for 'video/mp4': mpv.desktop
Registered applications:
mpv.desktop
smplayer.desktop
Recommended applications:
mpv.desktop
smplayer.desktop
因此,在这种情况下,gio
将使用mpv
该open
文件clip.mp4