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)
An alternative to get the absolute path in Ruby:
realpath() {ruby -e "require 'Pathname'; puts Pathname.new('$1').realpath.to_s";}
Works with no arguments (current folder) and relative and absolute file or folder path as agument.
This relative path to absolute path converter shell function
cd
andpwd
)..
and.
Code:
Sample:
Note: This is based on the answers from nolan6000 and bsingh, but fixes the file case.
I also understand that the original question was about an existing command line utility. But since this seems to be THE question on stackoverflow for that including shell scripts that want to have minimal dependencies, I put this script solution here, so I can find it later :)
For directories
dirname
gets tripped for../
and returns./
.nolan6000's function can be modified to fix that:
The
dogbane
answer with the description what is coming on:Explanation:
"$1"
dirname "$1"
cd "$(dirname "$1")
into this relative dir and get absolute path for it by runningpwd
shell command$(basename "$1")
echo
itThis is not an answer to the question, but for those who does scripting:
it handles / .. ./ etc correctly. I also seems to work on OSX
Try
readlink
which will resolve symbolic links: