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 other files.
I would like the script to go to the folder containing the input file, to execute further commands.
In Linux, how do I get the folder (and just the folder) from an input file?
Best Answer
To get the full path use:
To get the directory of a file:
You can also combine the two:
If
readlink -f
is not available on your system you can use this*: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:
if you wish to go back (while the script is running) to the original path, use
pushd
instead ofcd
, andpopd
when you are done.* While
myreadlink
above is good enough in the context of this question, it has some limitation relative to thereadlink
tool suggested above. For example it doesn't correctly follow a link to a file with differentbasename
.