Extract directory from path

StringBashPath

String Problem Overview


In my script I need the directory of the file I am working with. For example, the file="stuff/backup/file.zip". I need a way to get the string "stuff/backup/" from the variable $file.

String Solutions


Solution 1 - String

dirname $file

is what you are looking for

Solution 2 - String

dirname $file

will output

stuff/backup

which is the opposite of basename:

basename $file

would output

file.zip

Solution 3 - String

Using ${file%/*} like suggested by Urvin/LuFFy is technically better since you won't rely on an external command. To get the basename in the same way you could do ${file##*/}. It's unnecessary to use an external command unless you need to.

file="/stuff/backup/file.zip"
filename=${1##*/}     # file.zip
directory=${1%/*}     # /stuff/backup

It would also be fully POSIX compliant this way. Hope it helps! :-)

Solution 4 - String

For getting directorypath from the filepath:

file="stuff/backup/file.zip"
dirPath=${file%/*}/
echo ${dirPath}

Solution 5 - String

Simply use $ dirname /home/~username/stuff/backup/file.zip

It will return /home/~username/stuff/backup/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMattView Question on Stackoverflow
Solution 1 - StringMatthieuView Answer on Stackoverflow
Solution 2 - StringmatchewView Answer on Stackoverflow
Solution 3 - StringMagePartsView Answer on Stackoverflow
Solution 4 - StringUrvin ShahView Answer on Stackoverflow
Solution 5 - StringNishchay SharmaView Answer on Stackoverflow