如何通过 Shell (BASH/ZSH/SH) 获取文件的绝对路径? [英] How to obtain the absolute path of a file via Shell (BASH/ZSH/SH)?

查看:25
本文介绍了如何通过 Shell (BASH/ZSH/SH) 获取文件的绝对路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:是否有一个简单的 sh/bash/zsh/fish/... 命令来打印我提供给它的任何文件的绝对路径?

Question: is there a simple sh/bash/zsh/fish/... command to print the absolute path of whichever file I feed it?

用例:我在目录 /a/b 中,我想在命令行上打印文件 c 的完整路径,以便我可以轻松地将其粘贴到另一个程序中:/a/b/c.在处理长路径时,一个简单的小程序可能可以为我节省 5 秒左右的时间,最终加起来.所以让我惊讶的是我找不到一个标准的实用程序来做到这一点 - 真的没有吗?

Usage case: I'm in directory /a/b and I'd like to print the full path to file c on the command-line so that I can easily paste it into another program: /a/b/c. Simple, yet a little program to do this could probably save me 5 or so seconds when it comes to handling long paths, which in the end adds up. So it surprises me that I can't find a standard utility to do this — is there really none?

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

Here's a sample implementation, 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)

推荐答案

使用 realpath

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

这篇关于如何通过 Shell (BASH/ZSH/SH) 获取文件的绝对路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆