4

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?

2 Answers 2

7
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.

2
  • 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, 2012 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? Jul 21, 2014 at 17:04
2

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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .