1

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
Ramy
  • 117
  • 1
  • 7

2 Answers2

4

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`
Michael Hampton
  • 237,123
  • 42
  • 477
  • 940
1

A couple things to mention:

  • ls -dt [PATH]/* will also list files; that could be a problem if files are present in the directory.
  • you may want to use quotes, in case the directory name contains spaces.

So, a couple more quick options for you:

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

or, if supported by your ls command,

    cd "`ls -t --group-directories-first ~/workspace/docs/new-docs/Mapper/Documentation | head -1`"
trav
  • 11
  • 2