Get file directory path from file path

Talespin_Kit picture Talespin_Kit · May 25, 2011 · Viewed 442.2k times · Source

In Bash, if VAR="/home/me/mydir/file.c", how do I get "/home/me/mydir"?

Answer

paxdiablo picture paxdiablo · May 25, 2011

dirname and basename are the tools you're looking for for extracting path components:

$ export VAR='/home/pax/file.c'
$ echo "$(dirname "${VAR}")" ; echo "$(basename "${VAR}")"
/home/pax
file.c

They're not internal Bash commands but they're 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.