Chetan
Chetan

Reputation: 1537

Get the latest created directory from a filepath

I am trying to find what is the latest directory created in a given filepath.

ls -t sorts the content by timestamp of the of file or directory. But I need only directory.

Upvotes: 0

Views: 51

Answers (2)

dogbane
dogbane

Reputation: 274660

*/ matches directories.

So you could use the following command to get the most recent directory:

ls -td /path/to/dir/*/ | head -1

BUT, I would not recommend this because parsing the output of ls is unsafe.

Instead, you should create a loop and compare timestamps:

dirs=( /path/to/dir/*/ )
newest=${dirs[0]}
for d in "${dirs[@]}"
do 
    if [[ $d -nt $newest ]]
    then 
        newest=$d
    fi
done
echo "Most recent directory is: $newest"

Upvotes: 1

fedorqui
fedorqui

Reputation: 289835

You can use the fact that directories have a d in the beginning of its information.

Hence, you can do:

ls -lt /your/dir | grep ^d

This way, the last created directory will appear at the top. If you want it to be the other way round, with oldest at the top and newer at the bottom, use -r:

ls -ltr /your/dir | grep ^d

Upvotes: 2

Related Questions