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

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
up vote 4 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 '15 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.