Sign up ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

How can I separate the path and file elements in a bash loop like this?

for file in `find /my/path -name "*.ext"`
    #(path,onlyfile) = separate_path_and_file $file
    #dosomethingwith $onlyfile
share|improve this question

2 Answers 2

up vote 3 down vote accepted

You can't. But you can do them separately.

$ foo=/usr/local/bin/bar
$ echo "${foo##*/}"
$ echo "${foo%/*}"
share|improve this answer
Beautiful, thanks very much. – 719016 Jul 2 '12 at 8:57

I would suggest dirname and basename:

for file in `find /my/path -name "*.ext"`
    path="$(dirname $file)"
    onlyfile="$(basename $file)"
    # ...
share|improve this answer
This is much more readable than the accepted answer. – itsafire Sep 2 at 9:55

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.