Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

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

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!


$cd `ls -dt ~/workspace/docs/new-docs/Mapper/Documentation/* | head -1`
-bash: cd: drwxr-xr-x: No such file or directory
share|improve this question
up vote 4 down vote accepted

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`
share|improve this answer
+1 for a thorough answer but it's not working for me. see my update. – Ramy Mar 12 '14 at 15:39
Did you do something silly like alias ls to something containing the -l option? If so, try using /bin/ls in your command instead. – Michael Hampton Mar 12 '14 at 15:40
well i don't know but that seems to have worked! – Ramy Mar 12 '14 at 15:42
actually looks like I had this: alias ls='ls -n' I'll remove it. Not even sure what -n does (i inherited a lot of my aliases). – Ramy Mar 12 '14 at 15:43
hmmm...i see: -n, --numeric-uid-gid like -l, but list numeric user and group IDs – Ramy Mar 12 '14 at 15:45

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`"
share|improve this answer

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.