Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the latest file in directory [duplicate]

Tags:

bash

shell

unix

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?

like image 985
Ashot Avatar asked Feb 23 '13 14:02

Ashot


People also ask

How do I copy only the latest files in UNIX?

Running ls -t /path/to/source | head -1 will return the newest file in the directory /path/to/source so cp "$(ls -t /path/to/source | head -1)" /path/to/target will copy the newest file from source to target . The quotes around the expression are needed in order to deal with file names that contain spaces.

How do I find the last modified file?

File Explorer has a convenient way to search recently modified files built right into the “Search” tab on the Ribbon. Switch to the “Search” tab, click the “Date Modified” button, and then select a range. If you don't see the “Search” tab, click once in the search box and it should appear.

How do I copy the last modified file in Linux?

You can use the find command's mtime argument to find files that were last modified by a certain time and then use it's exec argument to copy them somewhere. -mtime n File's data was last modified n*24 hours ago.


2 Answers

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

like image 106
John Zwinck Avatar answered Oct 02 '22 12:10

John Zwinck


#!/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.

like image 42
janos Avatar answered Oct 02 '22 14:10

janos