I am trying to change a directory in a bash script in order to delete a file after it has been transferred. Here is my script and what I would like to do:

Please see line 5:

  1 #!/bin/bash
  2 name=$(date '+%y-%m-%d')
  3 tar -zcf /var/tmp/backups/splunkbackup$(date '+%y-%m-%d').tar.gz /opt/splunk/etc/
  4 rsync -avz /var/tmp/backups/splunkbackup* svc_splkbup@10.x.x.x:/var/log/splunk/backups/essearchhead
  5 cd /var/tmp/backups/splunkbackup*
  6 rm splunkbackup*
  • 1
    ..and the problem is? Though I can't see how /var/tmp/backups/splunkbackup* would expand to a single directory, since two lines above you created a file whose name matches the pattern. – ilkkachu Jan 16 '18 at 17:51
  • 3
    Why not just use rsync --remove-source-files? – DopeGhoti Jan 16 '18 at 17:56
  • @DopeGhoti would my command be: rsync -avz --remove-source-files /var/tmp/backups/splunkbackup* svc_splkbup@10.x.x.x:/var/log/splunk/backups/essearchhead – Wraiith Jan 16 '18 at 18:33
  • It would indeed. – DopeGhoti Jan 16 '18 at 18:42

rsync has a built-in method to do what you seem to be trying to do manually:

From man rsync:


This tells rsync to remove from the sending side the files (meaning non-directories) that are a part of the transfer and have been successfully duplicated on the receiving side.


The pattern /var/tmp/backups/splunkbackup* will likely expand to a list of files rather than to the name of a directory that you can change into.

My guess is that line five should read

cd /var/tmp/backups

or, that line five and six would be replaced by the single line

rm /var/tmp/backups/splunkbackup*

There is no need to change directories.

5 rm /var/tmp/backups/splunkbackup*

6 ``

although recursive force might be in order

5 rm -rf /var/tmp/backups/splunkbackup*

6 ``


Assuming you want to deal with just one archive file at a time, you could just save the filename to a variable:

file=/var/tmp/backups/splunkbackup$(date '+%y-%m-%d').tar.gz
tar -zcf "$file" /opt/splunk/etc/
rsync -avz "$file" svc_splkbup@10.x.x.x:/...
rm "$file"

Though you may want to only delete the file if the transfer succeeds, so this instead:

rsync -avz "$file" svc_splkbup@10.x.x.x:/... &&
  rm "$file"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.