问:有没有简单的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)

当前回答

用Homebrew回答

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

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

其他回答

这并不是问题的答案,但对于那些编写脚本的人来说:

echo `cd "$1" 2>/dev/null&&pwd||(cd "$(dirname "$1")";pwd|sed "s|/*\$|/${1##*/}|")`

它正确地处理/ .. / etc。我似乎也在OSX工作

在Ruby中获取绝对路径的另一种方法:

realpath() {ruby -e "require 'Pathname';将Pathname.new(1美元).realpath.to_s”;}

不带参数(当前文件夹)和相对和绝对文件或文件夹路径作为参数。

$ readlink -m FILE
/path/to/FILE

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

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

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

这个相对路径到绝对路径转换器的壳函数

不需要任何工具(只需要CD和pwd) 适用于目录和文件 处理. .和。 处理目录或文件名中的空格 要求文件或目录存在 如果给定路径上不存在,则返回零 将绝对路径作为输入处理(基本上是传递它们)

代码:

function abspath() {
    # generate absolute path from relative path
    # $1     : relative filename
    # return : absolute path
    if [ -d "$1" ]; then
        # dir
        (cd "$1"; pwd)
    elif [ -f "$1" ]; then
        # file
        if [[ $1 = /* ]]; then
            echo "$1"
        elif [[ $1 == */* ]]; then
            echo "$(cd "${1%/*}"; pwd)/${1##*/}"
        else
            echo "$(pwd)/$1"
        fi
    fi
}

示例:

# assume inside /parent/cur
abspath file.txt        => /parent/cur/file.txt
abspath .               => /parent/cur
abspath ..              => /parent
abspath ../dir/file.txt => /parent/dir/file.txt
abspath ../dir/../dir   => /parent/dir          # anything cd can handle
abspath doesnotexist    =>                      # empty result if file/dir does not exist
abspath /file.txt       => /file.txt            # handle absolute path input

注意:这是基于nolan6000和bsingh的答案,但修复了文件大小写。

我也理解最初的问题是关于一个现有的命令行实用程序。但由于这似乎是关于stackoverflow的问题,包括shell脚本,希望有最小的依赖关系,我把这个脚本解决方案放在这里,所以我可以稍后找到它:)