I know I can find a directory that's most recently modified by doing ls -ltr, but the last modified item might be a file, not a directory. Secondly I still have to type the directory name. My directory name is like a hash code, which is not really readable and it's quite painful to type each time.

Any easy one-liner to do so?

cd "$(ls -dt */ | head -1)"

Save this as an alias in ~/.bashrc, e.g.

alias lcd='cd -- "$(ls -dt -- */ | head -1)"'

and now lcd in any directory will change to the most recently changed directory in the current directory.

  • Keep in mind that the timestamp ls is checking here doesn't recurse - ie, it does not find the most recently modified file anywhere in the tree. It only measures direct changes to that directory. – Daenyth Mar 29 '12 at 18:51
  • This doesn't work for me. I get the error -bash: cd: mydir/: No such file or directory where mydir is the last modified directory. It seems to find the right directory but something is causing cd to fail. Any ideas? – Patrick Marchwiak Jul 21 '14 at 17:04

Adding this function to my ~/.bashrc works for me

function lcd(){
cd $(ls -v1td --color=never */ | head -1)

If I try to define it as an alias, the expression gets evaluated once when the shell starts and always tries to cd to the same subdirectory in my home directory. Without the --color=never statement, I get the error -bash: cd: mydir/: No such file or directory mentioned in another comment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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