I want to go in the directory on the basis of highest directory number.

Path: /home/cg/root/2018/01. Inside this path I have multiple directories as below

So on..

In this case highest directory is 17 so I want to move in 17 directory... If a directory named 18 exists then want to go in 18.

Is there any way which can be done using the cd command?

Like :

cd /home/cg/root/2018/01/$(ls |tail -1)
  • gratuitous zsh: cd $(zsh -c 'echo *(/on[-1])')
    – Jeff Schaller
    Jan 18, 2018 at 19:30
  • If any of the answers solved your problem, please accept it by clicking the checkmark next to it. Thank you!
    – Jeff Schaller
    May 16, 2018 at 10:50

5 Answers 5


You can use find sort and head to do this

cd $(find /home/cg/root/2018/01/* -type d | sort -r | head -1) should do the trick

  • Thanks for quick turn around, however I got below exception. Find: paths must precede expression......
    – Satya
    Jan 18, 2018 at 19:45
  • 3
    The correct syntax is: cd $(find /home/cg/root/2018/01 -type d | sort -r | head -1) Jan 18, 2018 at 19:48

This will do it

cd $(ls /home/cg/root/2018/01 | sort -n -r | awk 'NR==1 {print $1})

Using a (temporary) bash array inside a function:

cdhighest() {
  local dirs=(/home/cg/root/2018/01/*)
  cd -- "${dirs[-1]}"

Then just run cdhighest and it will take you to the directory under /home/cg/root/2018/01 that sorts last.



What you have pretty much looks like it should work, except that ls should of course be told to list the contents of the correct directory. But it wouldn't list the full paths and there's a bunch of other details. Plus the things listed in Why you shouldn't parse the output of ls(1)

Since the shell can list filenames, and it actually sorts them, we could use just printf with a glob:

$ cd "$(printf "%s\n" /home/cg/root/2018/01/*/ |tail -1)"

Of course, that requires the directory names don't contain newlines.


You can do it in simple way.

cd /home/cg/root/2018/01; cd `ls -r | head -n 1`

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .