问:有没有简单的sh/bash/zsh/fish/…命令打印任何文件的绝对路径我馈送它?

用例:我在目录/a/b中,我想在命令行上打印文件c的完整路径,这样我就可以轻松地将它粘贴到另一个程序:/a/b/c中。这很简单,但是在处理长路径时,一个小程序可能会为我节省5秒左右的时间。因此,让我感到惊讶的是,我找不到一个标准的实用程序来做这件事——真的没有吗?

下面是一个示例实现,abspath.py:

#!/usr/bin/python
# Author: Diggory Hardy <diggory.hardy@gmail.com>
# Licence: public domain
# Purpose: print the absolute path of all input paths

import sys
import os.path
if len(sys.argv)>1:
    for i in range(1,len(sys.argv)):
        print os.path.abspath( sys.argv[i] )
    sys.exit(0)
else:
    print >> sys.stderr, "Usage: ",sys.argv[0]," PATH."
    sys.exit(1)

当前回答

$ readlink -m FILE
/path/to/FILE

这比readlink -e FILE或realpath更好,因为即使文件不存在,它也能工作。

其他回答

#! /bin/bash

file="$@"
realpath "$file" 2>/dev/null || eval realpath $(echo $file | sed 's/ /\\ /g')

这弥补了realpath的缺点,将它存储在shell脚本fullpath中。你现在可以调用:

$ cd && touch a\ a && rm A 2>/dev/null 
$ fullpath "a a"
/home/user/a a
$ fullpath ~/a\ a
/home/user/a a
$ fullpath A
A: No such file or directory.

使用realpath

$ realpath example.txt
/home/username/example.txt

这里有一个只使用zsh的函数,我喜欢它的紧凑性。它使用了“A”扩展修饰符—参见zshexpn(1)。

realpath() { for f in "$@"; do echo ${f}(:A); done }

用Homebrew回答

Realpath是最好的答案,但如果你没有安装它,你必须首先运行brew install coreutils,它将安装coreutils与许多很棒的功能。编写一个自定义函数并导出它是太多的工作和错误的风险,对于这样的东西,这里有两行:

$ brew install coreutils
$ realpath your-file-name.json 

find命令可能有帮助

find $PWD -name ex*
find $PWD -name example.log

列出名称与模式匹配的当前目录中或下面的所有文件。你可以简化它,如果你只会得到几个结果(例如,目录接近树的底部包含几个文件),只是

find $PWD

我在Solaris 10上使用这个工具,Solaris 10没有提到的其他实用程序。