Bash CD Command – How to CD to the Most Recently Modified Child Directory

bashcd-commanddate

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.

Best Answer

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])
Related Question