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

查看:36
本文介绍了如何通过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天全站免登陆