Bash: get the directory and file name from a path
Use dirname and basename to split a path in a shell script.
To extract the directory or the file name from a path in a shell script, use dirname and basename.
$ VAR=/home/user/mydir/file.c
$ DIR=$(dirname "${VAR}")
$ echo "${DIR}"
/home/user/mydir
$ basename "${VAR}"
file.c
dirnamereturns the path without its last component (the parent directory).basenamereturns only the last component (the file name).- Always quote the variable so paths containing spaces work.