Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the absolute directory of a file in bash?

Tags:

linux

bash

shell

I have written a bash script that takes an input file as an argument and reads it.
This file contains some paths (relative to its location) to additional files used.

I would like the script to go to the folder containing the input file, to execute further commands.

So, how do I get the folder (and just the folder) from an input file? (In linux.)

like image 204
BobMcGee Avatar asked Jul 10 '13 17:07

BobMcGee


People also ask

How do I get absolute directory in bash?

pwd -P and get absolute 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?

2.1. To obtain the full path of a file, we use the readlink command. readlink prints the absolute path of a symbolic link, but as a side-effect, it also prints the absolute path for a relative path. In the case of the first command, readlink resolves the relative path of foo/ to the absolute path of /home/example/foo/.


1 Answers

To get the full path use:

readlink -f relative/path/to/file 

To get the directory of a file:

dirname relative/path/to/file 

You can also combine the two:

dirname $(readlink -f relative/path/to/file) 

If readlink -f is not available on your system you can use this*:

function myreadlink() {   (   cd "$(dirname $1)"         # or  cd "${1%/*}"   echo "$PWD/$(basename $1)" # or  echo "$PWD/${1##*/}"   ) } 

Note that if you only need to move to a directory of a file specified as a relative path, you don't need to know the absolute path, a relative path is perfectly legal, so just use:

cd $(dirname relative/path/to/file) 

if you wish to go back (while the script is running) to the original path, use pushd instead of cd, and popd when you are done.


* While myreadlink above is good enough in the context of this question, it has some limitation relative to the readlink tool suggested above. For example it doesn't correctly follow a link to a file with different basename.

like image 105
Chen Levy Avatar answered Oct 07 '22 10:10

Chen Levy