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?
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.
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.
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.
Add the -d
argument to ls. That way it will always print just what it's told, not look inside directories.
#!/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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With