Wondering if there's an easy and/or portable way to say "change to the most recently modified child directory." I can use ls and awk but there's probably a better way.

cd $( ls -ltrd */ | tail -1 | awk '{ print $8 }' )

I have to run a command in an "output files" directory with hundreds of subdirectories and 99% of the time I want to go to the most recently changed directory. I don't know what the names of the directories will be in advance.

  • 1
    Why not cd $(ls -v1td */ | head -1)? – Pablo Castellazzi Jul 13 '11 at 22:48
  • Good point...I'm not as familiar with ls options as I should be... – twblamer Jul 13 '11 at 23:30

Assuming your directories don't contain any unprintable characters:

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

(note that it will also consider symlinks to directories).

If you don't mind switching to zsh:

cd ./*(/om[1])

Or to include symlinks to directories as in the first example:

cd ./*(-/om[1])


  # cd into the last directory modified/created in pwd
   ls -p | grep / | tail -1 | pbcopy; str=$(pbpaste); cd $str
  • Why put the directory name on the clipboard? Also, ee what happens if the directory name contains a space - quite a common occurrence these days. – roaima Sep 10 '17 at 23:38
  • Using the clipboard allows for ease of further operations if you desire. – jasonleonhard Sep 10 '17 at 23:41
  • If you really want you can add further fields relatively easy. instead of {print$9} you can use {print$9,$10,$11} as many as you desire. – jasonleonhard Sep 10 '17 at 23:46
  • I have revised my answer to account for white space. – jasonleonhard Sep 10 '17 at 23:56
  • Here is a rough explanation: explainshell.com/… – jasonleonhard Sep 11 '17 at 0:03

Try this short versioned command

cd $(ls -t | head -n 1)   
  • That only works if the most recently modified file in the current directory is of type directory (or symlink to directory) and it's name doesn't contain blanks or wildcards or newlines and doesn't start with -, so it's hardly an improvement over the already accepted answer. – Stéphane Chazelas Feb 9 '18 at 15:32

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.