How to combine ls and cd commands in Unix

5

1

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.

Petro Semeniuk

Posted 2010-12-10T02:46:00.600

Reputation: 153

It also gives you files. You can't cd to a file. – gbarry – 2010-12-10T03:08:38.760

Migrate this question to Super User? – Peter Mortensen – 2011-01-22T09:47:21.147

Answers

10

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)"

Matthew Flaschen

Posted 2010-12-10T02:46:00.600

Reputation: 2 370

3I'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 – 2010-12-10T03:28:59.263

@camh, good suggestion. – Matthew Flaschen – 2010-12-10T03:34:42.253

Protect the command substitution with double quotes, or else it won't work when the directory contains spaces. – marco – 2011-01-22T12:12:20.527

2

solution using backticks:

cd `ls -th | head -1`

Naytzyrhc

Posted 2010-12-10T02:46:00.600

Reputation: 121

2

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.

user476622

Posted 2010-12-10T02:46:00.600

Reputation:

1

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.

Neilvert Noval

Posted 2010-12-10T02:46:00.600

Reputation: 357

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. – ocodo – 2011-01-22T13:05:51.170