如何从命令行使用默认应用程序打开文件?

Oli*_*nde 219 command-line

在 Nautilus 中,当您双击一个文件时,它将使用与文件扩展名关联的默认应用程序打开它。例如,.html 文件将在 Web 浏览器中打开,而 .pdf 将使用文档查看器打开。有没有办法从命令行(即open path/filename)中重现相同的行为?我问是因为我喜欢从命令行浏览我的文件系统,但有时不记得哪个应用程序。打开什么。

ane*_*hep 284

我认为xdg-open是您正在寻找的命令。

NAME
       xdg-open - opens a file or URL in the user's preferred application

SYNOPSIS
       xdg-open {file | URL}

       xdg-open {--help | --manual | --version}

DESCRIPTION
       xdg-open opens a file or URL in the user's preferred application. If a
       URL is provided the URL will be opened in the user's preferred web
       browser. If a file is provided the file will be opened in the preferred
       application for files of that type. xdg-open supports file, ftp, http
       and https URLs.
Run Code Online (Sandbox Code Playgroud)

例如: xdg-open index.php

这将在 gedit 中打开 index.php(如果您使用的是 gnome)。

如果你想在浏览器中打开一个 url

xdg-open http://google.com
Run Code Online (Sandbox Code Playgroud)

这将在您的默认浏览器中打开 google.com。


xdg-open是一个包装脚本-它将使用桌面环境的工具(gio opengvfs-openkde-opengnome-opendde-openexo-open,和其他此类工具的主机)。它也是默认安装的,并且很可能适用于过去、当前和未来的版本(另一方面,gvfs-opengnome-open已被弃用,可能在未来版本中不可用)。

  • 缩短此命令的简单方法是使用别名。`别名o='xdg-open'`。把它放在你的 `.bash_aliases` 文件中,以便每次启动时加载别名。`nano ~/.bash_aliases` 然后使用 `CTRL+SHIFT+V` 粘贴到 `nano` 中。 (7认同)
  • 在 Gnome 上:`gnome-open` 和在 KDE 上:`kde-open` 有效。 (2认同)
  • 对于像我这样的其他新手,`xdg` 代表 [*X (cross) Dekstop Group*](https://www.reddit.com/r/linuxmasterrace/comments/jiizsm/what_does_xdg_mean/) (2认同)

she*_*lic 50

xdg-opengnome-open

xdg-open 是最通用的方式(也适用于 KDE)


jes*_*ght 17

如果你想:

  • 为此命令创建别名(例如open
  • 隐藏命令的输出
  • 之后继续使用这个终端

你可以使用这个.bashrc 函数

function open () {
  xdg-open "$@">/dev/null 2>&1
}
Run Code Online (Sandbox Code Playgroud)

  • 替代方案是一个更简单的版本,不会隐藏输出或移动到后台:`alias o='xdg-open`。 (3认同)