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.)
pwd -P and get absolute path.
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.
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/.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With