ls, gives me all directories

ls -trh, gives me all directories sorted by date (newest last)

ls -dtrh */ | tail -1, gives me name of latest directory (by date)

Is it possible to somehow incorporate the ls and cd commands, so I could navigate to the latest directory. Something logically equal to ls -trh | tail -1 | cd, but working.

link|improve this question
It also gives you files. You can't cd to a file. – gbarry Dec 10 '10 at 3:08
Thanks, I've just updated command to show folders only – Petro Semeniuk Dec 10 '10 at 3:12
Migrate this question to Super User? – Peter Mortensen Jan 22 '11 at 9:47
feedback

migrated from stackoverflow.com Jan 22 '11 at 10:51

This question came from our site for professional and enthusiast programmers.

4 Answers

up vote 10 down vote accepted
cd "$(ls -trh | tail -1)"

This uses the output of the the ls|tail pipeline as the command-line arguments to cd.

EDIT: camh is correct that this should give better performance, because head won't go through the lines you're ignoring.

cd "$(ls -th | head -1)"
link|improve this answer
3  
I'd suggest instead of reverse sorting and using tail, you use a normal sort and use head. That way it processes less data: cd $(ls -th | head -n 1) (I know the OP used -r|tail, but we can improve on that) – camh Dec 10 '10 at 3:28
@camh, good suggestion. – Matthew Flaschen Dec 10 '10 at 3:34
Protect the command substitution with double quotes, or else it won't work when the directory contains spaces. – marco Jan 22 '11 at 12:12
@marco, thanks, fixed. – Matthew Flaschen Jan 22 '11 at 13:00
feedback

solution using backticks:

cd `ls -th | head -1`
link|improve this answer
feedback

I have done an alias for my own use:

alias cdu='cd $(ls -rtd */ | tail -1)'

this will put you in last modified/created directory in your position.

link|improve this answer
feedback

Use this simple command:

cd `ls -t`

The character <`> is a backtick character. Not an apostrophe.

This will go to the latest directory. Try it.

link|improve this answer
It will probably not, and is more likely to return a "too many arguments" error. I say probably, because it will work if a single directory is in the current-dir. – slomojo Jan 22 '11 at 13:05
feedback

Your Answer

 
or
required, but never shown

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