21

I need to get the latest directory name in a folder which start with nlb.

#!/bin/sh

cd /home/ashot/checkout
dirname=`ls -t nlb* | head -1`
echo $dirname

When the folder contains many folders with name starting nlb, this script works fine, but when there is only one folder with name starting nlb, this script prints the latest file name inside that folder. How to change it to get the latest directory name?

Ashot
  • 10,807
  • 14
  • 66
  • 117
  • 1
    Possible duplicate of [Get most recent file in a directory on Linux](https://stackoverflow.com/q/1015678/608639) – jww Oct 15 '18 at 02:43

2 Answers2

14

Add the -d argument to ls. That way it will always print just what it's told, not look inside directories.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
8
#!/bin/sh

cd /home/ashot/checkout
dirname=$(ls -dt nlb*/ | head -1)
echo $dirname

As the other answer points it out, you need the -d to not look inside directories.

An additional tip here is appending a / to the pattern. In the question you specified to get the latest directory. With this trailing / only directories will be matched, otherwise if a file exists that is the latest and matches the pattern nlb* that would break your script.

I also changed the `...` to $(...) which is the modern recommended writing style.

janos
  • 120,954
  • 29
  • 226
  • 236