简体   繁体   中英

How to append the timestamp of a process to the name of a file in Unix

I have a directory /home/user/ingest/ which has many files inside it with varying sizes. I need to move every file inside this folder into /home/user/ingest/inbox every two minutes. There might be a situation where the first file might take more than 2 mins to move into /home/user/ingest/inbox . In which case when its moving the second file, it SHOULDN'T take the first file as well. Which is why I thought to append the timestamp to the name of files at the time of moving. Is there anyway to do this in shell scripting?

And I also understand that usingh crontab might help me in scheduling the execution of the shell script every two minutes. I have a basic idea of cron but for my particular requirement, how can I check whether the file is being loved every two minutes or not?

You can do that with this bash script:

#!/bin/bash

TIMESTAMP=$(date +%s)

for f in /home/user/ingest/*
do
   if [ -f "$f" ]; then
      name=$(basename "$f")
      mv $f /home/user/ingest/inbox/${name}_${TIMESTAMP}
   fi
done

The ${TIMESTAMP} is the number of seconds since the epoch (Jan 1970). The for loop iterates through everything in the /home/user/ingest/ directory, and the if statement checks to see if the file is a regular file (not directory, not symlink), and then the file is moved to /home/user/ingest/inbox/ with the timestamp appended to the end.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM