0

Requirement is to move the files from source to archive folder adding timestamp I have created the below script but it is not moving the date which i am passing as wild card

File name: Test_20100101.txt
sourcedir=/projects/source
archivedir=/projects/archive
FILE="$1"

for file in $1; do
    fileroot=$1
  mv -i "$sourcedir/$1"* "$archivedir/$1_$(date +"%Y%m%d_%H%M%S")"
done

while executing i am running the script as below

./archfiles.sh Test_

but the output is coming as

Test__20200107_092902

the actual output should be

Test_20100101_20200107_092902.txt

can you please help me on this

  • Related question: https://unix.stackexchange.com/questions/560010/copy-files-with-wild-card-and-add-timestamp – AdminBee Jan 07 '20 at 15:14

1 Answers1

0

It doesn't make sense to use a for loop when you don't use the loop variable file. If you want to process the files from a wildcard expansion one by one you have to use the wildcard in the for statement, not in the loop body.

(It looks as if you modified the code from the related question Copy files with wild card and add timestamp without understanding it.)

If the files are located in a different directory $sourcedir you have to either (1) specify $sourcedir together with the wildcard or (2) change the current directory to $sourcedir.

Example 1:

for file in "$sourcedir/$1"*
do
    base="${file##*/}"
    mv -i "$sourcedir/$base" "$archivedir/${base}_$(date +"%Y%m%d_%H%M%S")"
done

Example 2 (assuming sourcedir and archivedir are absolute paths):

cd "$sourcedir"
for file in "$1"*
do
    mv -i "$file" "$archivedir/${file}_$(date +"%Y%m%d_%H%M%S")"
done

(All code is untested.)

Bodo
  • 6,068
  • 17
  • 27