bash/fish command to print absolute path to a file

2019-01-03 08:01发布

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

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?

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)

标签: bash shell path
17条回答
看我几分像从前
2楼-- · 2019-01-03 08:32

Try realpath.

$ realpath example.txt
/home/username/example.txt
查看更多
smile是对你的礼貌
3楼-- · 2019-01-03 08:32

The find command may help

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

Lists all the files in or below the current directory with names matching the pattern. You can simplify it if you will only get a few results (e.g. directory near bottom of tree containing few files), just

find $PWD

I use this on Solaris 10, which doesn't have the other utilities mentioned.

查看更多
爷的心禁止访问
4楼-- · 2019-01-03 08:33
$ readlink -m FILE
/path/to/FILE

This is better than readlink -e FILE or realpath, because it works even if the file doesn't exist.

查看更多
神经病院院长
5楼-- · 2019-01-03 08:35
#! /bin/sh
echo "$(cd "$(dirname "$1")"; pwd -P)/$(basename "$1")"
查看更多
放我归山
6楼-- · 2019-01-03 08:36
#! /bin/bash

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

This makes up for the shortcomings of realpath, store it in a shell script fullpath. You can now call:

$ 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.
查看更多
登录 后发表回答