how to pipe results from LS to CD in ubuntu

Ramy asked:

I’d like to ls for the latest created directory in a given directory (we create a new folder for each release) and then cd to that directory. I’d like to create an alias for this so I don’t have to remember how to get to the latest directory every time I need to.

Here’s what I’ve tried:

ls -ltr ~/workspace/docs/new-docs/Mapper/Documentation/ | tail -1 | cd
cd $(ls -ltr ~/workspace/docs/new-docs/Mapper/Documentation/ | tail -1)

the problem seems to be that if I order the results I end up with the permissions on the file as output. Any help is greatly appreciated!

UPDATE:

$cd `ls -dt ~/workspace/docs/new-docs/Mapper/Documentation/* | head -1`
-bash: cd: drwxr-xr-x: No such file or directory

My answer:


Well, you did specify the -l option to ls, which results in long output. Try dropping it.

ls -tr ~/workspace/docs/new-docs/Mapper/Documentation/

You’ll also need to ensure that the path gets prepended to the directory name you want. Do this by adding * to the path and specifying the -d option to ls.

ls -dtr ~/workspace/docs/new-docs/Mapper/Documentation/*

To improve performance you should also pipe to head and not reverse the sort.

ls -dt ~/workspace/docs/new-docs/Mapper/Documentation/* | head -1

The final command is:

cd `ls -dt ~/workspace/docs/new-docs/Mapper/Documentation/* | head -1`

View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.