Search code examples
bashshellfish

Go to parent directory inline


I was wondering if it’s possible to go to parent directory of a file inline. I know I could type cd .. and it would. However, what if I wanted do something like echo $(find . -name “xyz.png”)..and it would return the parent directory of the file instead of the path to file. Or instead of a file I search for a folder, and want to return path to the parent directory.


Solution

  • You could use dirname to strip off the last part of a path. Combined with find in your examples it would give you just the parent directory of whatever was found. You could use that in cd as in cd $(find -name "xyz.png" | xargs dirname) if that's the sort of thing you're trying to do.

    You can also use the -type d option to find to have it only find directories if you want to match directory names instead of filenames.