Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
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
up vote 4 down vote accepted

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])
share|improve this answer
Looks good, thanks – twblamer Jul 13 '11 at 23:31

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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