0

I would like to know if it's possible to grab the newest folder inside a directory and use that in a command automatically for linux. What I am trying to achieve is the following:

There is a folder called/home/admin/web/backups/FTP/ where a software drops folders with bi-weekly backups (so inside of "FTP" you'll find folders like 2021-03-28, 2021-03-30, etc.)

I sync that over to a drive utilizing rclone (rclone copy -P /home/admin/web/backups/FTP/XXX drive:XXX) XXX being the latest folder created (I type this out manually) so in this case it'd be 2021-03-03 for example.

Is there a way to grab the name of the newest folder (say the newest folder is 2021-04-03) and then replace the "XXX" after FTP/ and drive: in that command and execute it?

Thanks in advance!

Juan
  • 13
  • 2
  • By "newest folder" you mean "most recently created", "most recently modified", or "most recent date inside the name" ? I guess what I am asking is, can we use any of the three or does it have to be based on the name of the folder? – Jerry Jeremiah Mar 31 '21 at 04:10
  • The contents of the folders are not going to be modified at all so most recently created/modified would be the same and that's what I'd like to use as a criteria! – Juan Mar 31 '21 at 04:15
  • I hope someone can see this albeit the question being closed - I have since utilized the solution given but I have ran into an issue. I'm trying to use the suggested code in a bash script and it ultimately fails. My code: #!/bin/bash BACKUPDIR=$(ls -td /home/admin/web/REDACTED/FTP/*/ | head -1) rclone copy -P "/home/admin/web/REDACTED/FTP/$BACKUPDIR" drive:$BACKUPDIR However, when I run this command the var that is put into BACKUPDIR is 2021-03-31 (the creation date of the backup file, and not of the latest folder that should be 2021-03-28) – Juan Mar 31 '21 at 04:41
  • Sorry Jerry, I was being very unclear and my last question was terribly formulated. The command works. However inside $BACKUPDIR what ends up being stored is the PATH to the latest folder. So it ends up being /home/admin/web/REDACTED/FTP/2021-03-28. While I do need that path to use in the rclone command's first section, after drive: I need only that "2021-03-28". How would I go about cropping/copying off only that part? (The folder name) – Juan Mar 31 '21 at 05:02
  • What about `BACKUPDIRPATH=$(ls -td /home/admin/web/REDACTED/FTP/*/ | head -1)` followed by `BACKUPDIRNAME=$(basename $BACKUPDIRPATH)` – Jerry Jeremiah Mar 31 '21 at 05:19
  • Works perfectly. Thank you so much Jerry! – Juan Mar 31 '21 at 05:22
  • If your system doesn't have basename then `BACKUPDIRNAME=$(tmp=${BACKUPDIRPATH%/};echo ${tmp##*/}) ` – Jerry Jeremiah Mar 31 '21 at 05:25

0 Answers0