Linux get absolute path

How to get full path of a file?

@J0hnG4lt: that’s because you installed coreutils with homebrew and changed your PATH to point to the unprefixed binaries. Installing coreutils, leaving PATH alone, and using «greadlink» would work as well.

From the man page of readlink : Note realpath is the preferred command to use for canonicalization functionality.

I suppose you are using Linux.

I found a utility called realpath in coreutils 8.15.

realpath -s file.txt /data/ail_data/transformed_binaries/coreutils/test_folder_realpath/file.txt 

Since the question is about how to get the full/absolute path of a file and not about how to get the target of symlinks, use -s or —no-symlinks which means don’t expand symlinks.

As per @styrofoam-fly and @arch-standton comments, realpath alone doesn’t check for file existence, to solve this add the e argument: realpath -e file

realpath was committed to the coreutils repo end of 2011, release 8.15 was done in January 2012, I answered the question (with the readlink suggestion) in March 2011 🙂

realpath doesn’t check for the file’s existence, it just resolves paths. Asking for a full path of a not existing file should result in an error.

The following usually does the trick:

 echo "$(cd "$(dirname "$1")" && pwd -P)/$(basename "$1")" 

Hello. I found this answer best to my requirement. Can you explain how can I use a local variable instead of command line parameter(i.e. $1)

LOCAL_VARIABLE=»filename.txt» && echo $(cd $(dirname «$LOCAL_VARIABLE») && pwd -P)/$(basename «$LOCAL_VARIABLE»)

@SopalajodeArrierez Because readlink doesn’t work if the file is a symlink, it will show you the target of the symlink instead of the symlink itself.

I like this, because readlink takes me back to the parent dir where the symbolic link generates from, but this ignores it.

I know there’s an easier way that this, but darned if I can find it.

jcomeau@intrepid:~$ python -c 'import os; print(os.path.abspath("cat.wav"))' /home/jcomeau/cat.wav 
jcomeau@intrepid:~$ ls $PWD/cat.wav /home/jcomeau/cat.wav 

On Windows:

  • Holding Shift and right clicking on a file in Windows Explorer gives you an option called Copy as Path . This will copy the full path of the file to clipboard.

On Linux:

  • You can use the command realpath yourfile to get the full path of a file as suggested by others.
find $PWD -type f | grep "filename" 
find $PWD -type f -name "*filename*" 

Thanks! This inspired me to use a simpler find $PWD that works perfectly for me when it’s just a few files

If you are in the same directory as the file:

Replace file.txt with your target filename.

I know that this is an old question now, but just to add to the information here:

The Linux command which can be used to find the filepath of a command file, i.e.

You could use the fpn (full path name) script:

% pwd /Users/adamatan/bins/scripts/fpn % ls LICENSE README.md fpn.py % fpn * /Users/adamatan/bins/scripts/fpn/LICENSE /Users/adamatan/bins/scripts/fpn/README.md /Users/adamatan/bins/scripts/fpn/fpn.py 

fpn is not a standard Linux package, but it’s a free and open github project and you could set it up in a minute.

Читайте также:  Linux сетевая папка командная строка

Works on Mac, Linux, *nix:

This will give you a quoted csv of all files in the current dir:

ls | xargs -I <> echo "$(pwd -P)/<>" | xargs | sed 's/ /","/g' 

The output of this can be easily copied into a python list or any similar data structure.

Yes, comma separated full paths for all files in pwd, for a file just do ls ‘filename’ instead of just ‘ls’.

echo $(cd $(dirname "$1") && pwd -P)/$(basename "$1") 

This is explanation of what is going on at @ZeRemz’s answer:

  1. This script get relative path as argument «$1»
  2. Then we get dirname part of that path (you can pass either dir or file to this script): dirname «$1»
  3. Then we cd «$(dirname «$1») into this relative dir
  4. && pwd -P and get absolute path for it. -P option will avoid all symlinks
  5. After that we append basename to absolute path: $(basename «$1»)
  6. As final step we echo it

You may use this function. If the file name is given without relative path, then it is assumed to be present in the current working directory:

$ abspath file.txt /I/am/in/present/dir/file.txt 
$ abspath ../../some/dir/some-file.txt /I/am/in/some/dir/some-file.txt 
$ abspath "../../some/dir/another file.txt" /I/am/in/some/dir/another file.txt 

You can save this in your shell.rc or just put in console

function absolute_path < echo "$PWD/$1"; >alias ap="absolute_path" 

I was surprised no one mentioned located.

If you have the locate package installed, you don’t even need to be in the directory with the file of interest.

Say I am looking for the full pathname of a setenv.sh script. This is how to find it.

$ locate setenv.sh /home/davis/progs/devpost_aws_disaster_response/python/setenv.sh /home/davis/progs/devpost_aws_disaster_response/webapp/setenv.sh /home/davis/progs/eb_testy/setenv.sh 

Note, it finds three scripts in this case, but if I wanted just one I would do this:

$ locate *testy*setenv.sh /home/davis/progs/eb_testy/setenv.sh 

This solution uses commands that exist on Ubuntu 22.04, but generally exist on most other Linux distributions, unless they are just too hardcore for s’mores.

The shortest way to get the full path of a file on Linux or Mac is to use the ls command and the PWD environment variable.

 touch afile pwd /adir ls $PWD/afile /adir/afile 

You can do the same thing with a directory variable of your own, say d .

 touch afile d=/adir ls $d/afile /adir/afile 

Notice that without flags ls and echo are equivalent (for valid names of files in the current directory), so if you’re using echo for that, you can use ls instead if you want.

If the situation is reversed, so that you have the full path and want the filename, just use the basename command.

 touch afile basename $PWD/afile afile 

In a similar scenario, I’m launching a cshell script from some other location. For setting the correct absolute path of the script so that it runs in the designated directory only, I’m using the following code:

set script_dir = `pwd`/`dirname $0` 

$0 stores the exact string how the script was executed.

For e.g. if the script was launched like this: $> ../../test/test.csh , $script_dir will contain /home/abc/sandbox/v1/../../test

Читайте также:  Передача файлов линукс виндовс

voted for this as this is the easiest and most relevant. However if you type ./test.csh you will have a path ending with /test/.

For Mac OS X, I replaced the utilities that come with the operating system and replaced them with a newer version of coreutils. This allows you to access tools like readlink -f (for absolute path to files) and realpath (absolute path to directories) on your Mac.

The Homebrew version appends a ‘G’ (for GNU Tools) in front of the command name — so the equivalents become greadlink -f FILE and grealpath DIRECTORY .

Instructions for how to install the coreutils/GNU Tools on Mac OS X through Homebrew can be found in this StackExchange arcticle.

NB: The readlink -f and realpath commands should work out of the box for non-Mac Unix users.

I like many of the answers already given, but I have found this really useful, especially within a script to get the full path of a file, including following symlinks and relative references such as . and ..

dirname `readlink -e relative/path/to/file` 

Which will return the full path of the file from the root path onwards. This can be used in a script so that the script knows which path it is running from, which is useful in a repository clone which could be located anywhere on a machine.

basePath=`dirname \`readlink -e $0\`` 

I can then use the $ variable in my scripts to directly reference other scripts.

This worked pretty well for me. It doesn’t rely on the file system (a pro/con depending on need) so it’ll be fast; and, it should be portable to most any *NIX. It does assume the passed string is indeed relative to the PWD and not some other directory.

function abspath () < echo $1 | awk '\ # Root parent directory refs to the PWD for replacement below /^\.\.\// < sub("^", "./") >\ # Replace the symbolic PWD refs with the absolute PWD \ /^\.\// < sub("^\.", ENVIRON["PWD"])>\ # Print absolute paths \ /^\// \' > 

This is naive, but I had to make it to be POSIX compliant. Requires permission to cd into the file’s directory.

#!/bin/sh if [ $ = 0 ]; then echo "Error: 0 args. need 1" >&2 exit 1 fi if [ -d $ ]; then # Directory base=$( cd $; echo $ ) dir=$( cd $; echo $> ) if [ $ = / ]; then parentPath=$ else parentPath=$ fi if [ -z $ ] || [ -z $ ]; then if [ -n $ ]; then fullPath=$( cd $; echo $ ) else echo "Error: unsupported scenario 1" >&2 exit 1 fi fi elif [ $ = $ ]; then if [ -f ./$ ]; then # File in current directory base=$( echo $ ) parentPath=$( echo $ ) else echo "Error: unsupported scenario 2" >&2 exit 1 fi elif [ -f $ ] && [ -d $ ]; then # File in directory base=$( echo $ ) parentPath=$( cd $; echo $ ) else echo "Error: not file or directory" >&2 exit 1 fi if [ $ = / ]; then fullPath=$ fi fullPath=$ if [ ! -e $ ]; then echo "Error: does not exist" >&2 exit 1 fi echo $

Источник

Get Absolute File Path in Linux

Here are different ways to get the absolute file paths in Linux command line.

You can get the full path of a directory with the pwd command:

But how do you get the absolute path of a file in Linux?

There are several ways to print the full path of files:

Get file path in Linux

  • readlink
  • realpath
  • find
  • combining ls and pwd

Let me show you these commands one by one. But before that, I suggest brushing up on the basics of the absolute and relative path concept first.

The purpose of the readlink command is to resolve symbolic links. You can use it to display the full path of a file like this:

[email protected]:~$ readlink -f sample.txt /home/abhishek/sample.txt [email protected]:

Use realpath to get full file path

The realpath command is used for resolving the absolute file names. Among other uses, it can show the full path to a file.

Take a look at this example:

[email protected]:~$ realpath sample.txt /home/abhishek/sample.txt [email protected]:~$

If you use it with a symbolic link, it will show the real path of the original file. You can force it to not follow the symbolic link:

Here’s an example where it showed the full path to the source file by default and then I forced it to show the symbolic link, not its original file.

[email protected]:~$ realpath linking-park /home/abhishek/Documents/ubuntu-commands.md [email protected]:~$ realpath -s linking-park 

Use the find command to get the absolute file path

Here’s the thing with the find command. Everything is relative to the directory you give it for search location.

If you give it . it will show the relative path. If you give it the absolute path of the directory, you’ll get the absolute path of the files you are searching for.

Use the command substitution with the find command like this:

You can run it to find the full path of a single file:

[email protected]:~$ find $(pwd) -name sample.txt /home/abhishek/sample.txt

Or, you can use it with a bunch of files matching a certain pattern:

[email protected]:~/Documents/eBooks$ find $(pwd) -name "*.pdf" /home/abhishek/Documents/eBooks/think-like-a-programmer.pdf /home/abhishek/Documents/eBooks/linux-guide.pdf /home/abhishek/Documents/eBooks/absolute-open-bsd.pdf /home/abhishek/Documents/eBooks/theory-of-fun-for-game-design.pdf /home/abhishek/Documents/eBooks/Ubuntu 1804 english.pdf /home/abhishek/Documents/eBooks/computer_science_distilled_v1.4.pdf /home/abhishek/Documents/eBooks/the-art-of-debugging-with-gdb-and-eclipse.pdf

Now this one is a bit tricky and messy.

You can use the environment variable PWD with ls command like this to display the files and directories with their absolute path:

You get an output like this:

[email protected]:~/test$ ls -ld $PWD/* -r--rw-r-- 1 abhishek abhishek 0 Jul 27 16:57 /home/abhishek/test/file2.txt drwxrwxr-x 2 abhishek abhishek 4096 Aug 22 16:58 /home/abhishek/test/new 

However, to print the full path of a file with the ls command, you’ll have to use it like this:

Not the cleanest solution but it works.

[email protected]:~$ ls -l $PWD/sample.txt -rw-r--r-- 1 abhishek abhishek 12813 Sep 7 11:50 /home/abhishek/sample.txt [email protected]:~$ 

Conclusion

I showed four different ways to get the full file path in Linux. The find and ls commands are common while realpath and readlink are hardly known to many Linux users. It’s always good to learn new things, isn’t it?

Источник

Оцените статью
Adblock
detector