0

I'm working to make a small script to transfer some files with rsync. I'm stuck with a variable issue.

  • I have the folder: /home/folder_1/, which have the folders 20210725, 20210726, 20210727 and those will increment every day.
  • In every one of those folders I have a folder named folder_2 and inside it are the files that i want to transfer.
  • An example for full path: /home/folder_1/20210727/folder_2/*

As I need to make the transfer from machine 1 to machine 2 every day, I want to put the script in a cron and run it automatically every day.

To take the day of today in account, I write:

y=${BASH_REMATCH[1]}
m=${BASH_REMATCH[2]}
d=${BASH_REMATCH[3]}
BASEDATE=`date '+%Y%m%d'`
DATA=$(eval "echo $BASEDATE")

So if I say echo $DATA, it return 20210727 for today: 27 July 2021

But, when I put in a variable like that:

VAR_1='/home/folder_1/${DATA}/folder_2/*'

it is not working. echo $VAR_1 will return

/home/folder_1/${DATA}/folder_2/*

instead of what I want:

/home/folder_1/20210727/folder_2/*

I need that because my rsync command is like that:

rsync -av user@machine_1:${VAR_1} ${VAR_2}

and VAR_2 is the path to the new location on the machine_2:

VAR_2='/home/folder_3/folder_4/'

I just cannot figure out how to use the variable to return the correct path, with the date for every day.

Can you please help/advise in some way? Thank you in advance!

2

1 Answer 1

2

The problem you are experiencing is that variable expansion is disabled in single quotes. So, your assignment

VAR_1='/home/folder_1/${DATA}/folder_2/*'

should be changed to

VAR_1="/home/folder_1/${DATA}/folder_2/*"

instead. The double-quotes will still inhibit expansion of the glob characters (*) which is necessary since you want to pass this as an argument to rsync.

As a side-note:

  • It is recommended not to use all-uppercase names for shell variables unless you want to export them to the environment (imagine accidentally overwriting PATH e.g.).
  • When using shell variables (cf. your rsync invocation), it is recommended to double-quote them unless you want word splitting to happen. In most cases when dealing with filenames, you do not want that to happen, because the space is an allowed character in filenames.
  • You are mixing the old-style `...` and new-style $( ... ) notation for command substitutions. It is recommended to stick to the new style because that allows for ease of nesting.
  • It is unclear why you would need the
    DATA=$(eval "echo $BASEDATE")
    
    at all. It should be sufficient to simply assign
    DATA=$(date +%Y%m%d)
    

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .