In Bash, if VAR="/home/me/mydir/file.c"
, how do I get "/home/me/mydir"
?
Use os. path. dirname() to get the directory folder (name) from a path string.
Techopedia Explains Absolute PathAn absolute path always contains the root elements and the complete list of directories to locate the specific file or folder. All the information required to locate the file or folder is available in the absolute path.
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/.
dirname
and basename
are the tools you're looking for for extracting path components:
$ VAR='/home/pax/file.c' $ DIR="$(dirname "${VAR}")" ; FILE="$(basename "${VAR}")" $ echo "[${DIR}] [${FILE}]" [/home/pax] [file.c]
They're not internal bash
commands but they are part of the POSIX standard - see dirname
and basename
. Hence, they're probably available on, or can be obtained for, most platforms that are capable of running bash
.
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