Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving a file and adding the date to the filename

Tags:

bash

rename

mv

#!/bin/bash
while read server <&3; do   #read server names into the while loop    
  if [[ ! $server =~ [^[:space:]] ]] ; then  #empty line exception
    continue
  fi   
  echo "Connecting to - $server"
  #ssh "$server"  #SSH login
  while read updatedfile <&3 && read oldfile <&4; do     
    echo Comparing $updatedfile with $oldfile
    if diff "$updatedfile" "$oldfile" >/dev/null ; then
      echo The files compared are the same. No changes were made.
    else
      echo The files compared are different.
      # copy the new file and put it in the right location
      # make a back up of the old file and put in right location (time stamp)
      # rm the old file (not the back up)
      #cp -f -v $newfile

      # ****************************
      mv $oldfile /home/u0146121/backupfiles/$oldfile_$(date +%F-%T)
      # ****************************
    fi 
  done 3</home/u0146121/test/newfiles.txt 4</home/u0146121/test/oldfiles.txt
done 3</home/u0146121/test/servers.txt

The line between * is where I am having trouble with my script. It would output the file with both the date and filename. It just uses the date. I want it to do both.

like image 552
mkrouse Avatar asked Mar 23 '23 05:03

mkrouse


1 Answers

Variable names may contain underscores, so you can't have underscores immediately after bare variable names. In your case you're actually using an (undefined) variable $oldfile_ in the destination file name, so that the new name is constructed as "empty string + date". Put the variable name between curly brackets

mv $oldfile /home/u0146121/backupfiles/${oldfile}_$(date +%F-%T)

and the renaming should work as expected.

like image 152
Ansgar Wiechers Avatar answered Apr 06 '23 09:04

Ansgar Wiechers