0

I'm new to this, but I've been asked to write a bash script to SFTP a file from one server to another. The bash script will be run 4 times per day using CRON, just after the file below has been created. The client's website creates XML files containing orders 4 times per day. Each file is given a new name, with an incremental number. For example:

a_file-01.xml
b_file-01.xml
a_file-02.xml
b_file-02.xml
a_file-03.xml
b_file-03.xml

How can I find the newest file (which will also have the highest number)?

Quasímodo
  • 3,812
  • 14
  • 25
  • Does this answer your question? [Bash function to find newest file matching pattern](https://stackoverflow.com/questions/5885934/bash-function-to-find-newest-file-matching-pattern) – pjh Mar 13 '20 at 18:02

2 Answers2

0

A simple approach is to just use ls. You can order the files in a directory this way: ls -t. The newest file is on the top of the list. So this will work:

NEWEST=$( ls -t | head -1 )

However, you may want to glob to get your results ( to avoid files that are unintentionally in your directory ):

NEWEST=$( ls -t *file*.xml | head -1 ) 
Mark
  • 4,249
  • 1
  • 18
  • 27
  • Thanks for your reply @Mark. Having now got the list, I need to copy/move the latest file to another folder. I have this code, but I can't get it to work. Testing it as part of a CRON job gives an error. # get newest file in folder cd /public_html/uploads/foldername/ NEWEST=$( ls -t | head -1 ) cp /public_html/uploads/foldername/"$NEWEST" /public_html/orders/"$NEWEST" quit EOF My cron is as follows: 30 06 * * * /opt/xmlbackup.sh Thanks! – willothewisp Mar 24 '20 at 12:17
0

Here is one function to do that.

latest () { 
    local file latest;
    for file in "${1:-.}"/*.xml; do
      [[ $file -nt $latest ]] && latest=$file;
    done
    printf '%s\n' "$latest"
}

Run that inside the directory where the xml files are.

latest

should print out the latest modified file regardless of the number.

Jetchisel
  • 7,493
  • 2
  • 19
  • 18