Search code examples
bashsshlssubshell

bash: how to display the name of the first directory that contains a certain file


I have this:

ls */file
dir1/file dir2/file dir3/file

But I need just the first directory name, like this: dir1

I did this:

IFS="/" read foo bar <<< "$(ls */file 2>/dev/null)"
echo $foo
dir1

And it works, but now I have a problem with subshell expansion over ssh. Is there a more elegant way (without subshells or sed) to do this?

If not, I'll then post a question regarding a completely different issue - expanding subshells over ssh.


Solution

  • for F in */file; do
        D=${F%%/*}
        break
    done
    

    Another:

    F=(*/file); D=${F%%/*}