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?

1

2 Answers 2

14

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

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.