Getting to the Bottom of Things
Problem
You work in a lot of narrow but deep directory structures, where all the content is at the bottom and you’re tired of having to manually cd so many levels.
Solution
alias bot='cd $(dirname $(find . | tail -n 1))'
Discussion
This use of find in a large directory structure such as /usr could take a while and isn’t recommended.
Depending on how your directory structure is set up, this may not
work for you; you’ll have to try it and see. The find
. will simply list all the files and
directories in the current directory and below, the tail -n 1
will grab the last line, dirname
will extract just the path, and
cd
will take you there. It may be
possible for you to tweak the command to get it to put you in the right
place. For example:
alias bot='cd $(dirname $(find . | sort -r | tail -n 5 | head -1))' alias bot='cd $(dirname $(find . | sort -r | grep -v 'X11' | tail -n 3 | head -1))'
Keep trying the part in the inner-most parentheses, especially tweaking the find command, until you get the results you need. Perhaps there is a key file or directory at the bottom of the structure, in which case the following function might work:
function bot { cd $(dirname $(find . | grep -e "$1" | head -1)); }
Note that aliases can’t use arguments, so this must be a function.
We use grep rather than a -name
argument to find
because grep is much more flexible. Depending on your structure, you might want
to use tail instead of head.
Again, test the find command first.
See Also
Get bash Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.