Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to obtain the absolute path of a file via Shell (BASH/ZSH/SH)?

Tags:

bash

shell

path

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 <[email protected]>
# 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)
like image 427
dhardy Avatar asked Oct 12 '10 13:10

dhardy


People also ask

How do I find absolute path in bash?

In this case, first, we need the current script's path, and from it, we use dirname to get the directory path of the script file. Once we have that, we cd into the folder and print the working directory. To get the full or absolute path, we attach the basename of the script file to the directory path or $DIR_PATH.

How do I find the absolute path of a file?

You can determine the absolute path of any file in Windows by right-clicking a file and then clicking Properties. In the file properties first look at the "Location:" which is the path to the file.

How do I find the absolute path of a file in Linux?

The pwd command prints the current/working directory, telling where you are currently located in the filesystem. This command comes to your rescue when you get lost in the filesystem, and always prints out the absolute path.

What is absolute path in shell?

An absolute path is defined as the specifying the location of a file or directory from the root directory(/). In other words we can say absolute path is a complete path from start of actual filesystem from / directory.


2 Answers

Use realpath

$ realpath example.txt
/home/username/example.txt
like image 198
Benjamin Bannier Avatar answered Nov 01 '22 05:11

Benjamin Bannier


Try readlink which will resolve symbolic links:

readlink -e /foo/bar/baz
like image 358
Dennis Williamson Avatar answered Nov 01 '22 05:11

Dennis Williamson