0

I transfer a file from a remote server to my local server. If this is done I do a diff to check if both files are identical to check if the transfer was successful. So I do this:

ssh -o StrictHostKeyChecking=no -l ${SSH_USER} ${SSH_HOST} "cat $FOLDERPATH_REMOTE.tar.gz" | diff - "$FOLDERPATH_LOCAL.tar.gz"
    if [[ $? -eq 0 ]]; then
        echo "\n##### Remove file from remote machine #####\n"
        rm -f $FOLDERPATH_REMOTE.tar.gz
    fi

When I do this, I get always an error like this:

diff: /home/backups/test.tar.gz: No such file or directory

and

[[: not found

But when I do a cat /home/backups/test.tar.gz the file exists. So somehow the command does not distinguish between local and remote system and the if after the ssh command is not executing.

Does anybody knows what I am doing wrong?

P.S: And another beginner question: When do I have to write variables like this ${VAR} and when like $VAR?

7
  • [[ is a bash syntax, but you seem to be running under a different shell. – choroba Jan 8 at 16:48
  • I also tried it with: ssh -o StrictHostKeyChecking=no -l ${SSH_USER} ${SSH_HOST} "cat $FOLDERPATH_REMOTE.tar.gz" | diff - "$FOLDERPATH_LOCAL.tar.gz" /bin/bash << EOF if [[ $? -eq 0 ]]; then rm -f $FOLDERPATH_REMOTE$FILEPREFIX-$DATETIME.tar.gz fi EOF But even then I get a No such file or directory error, as the script does not to understand that it should compare on two different systems. – user611630 Jan 8 at 17:40
  • Don't include code into comments. You can update the question with additional information. – choroba Jan 8 at 18:00
  • Also, you probably want to rm the local file, not the remote one, right? – choroba Jan 8 at 18:01
  • No. Is everything that I run behind bin/bash <<EOF done on the remote side? I think so. Then it would be correct to rm the remote file as I have copied this one to my local machine and do not need it anymore on the remote server. – user611630 Jan 8 at 19:08
0

Use rsync with --remove-source-files.

rsync --remove-source-files "${SSH_USER}@${SSH_HOST}:$FOLDERPATH_REMOTE.tar.gz" \
                            "$FOLDERPATH_LOCAL.tar.gz"

In response to your other questions, you need to use ${VAR} when putting the variable name in the middle of a word-- - and . are fine separators, but _ is not.

echo $var.txt      # same as ${var}.txt
echo $var-2020.txt # same as ${var}-2020.txt
echo $var_2020.txt # same as ${var_2020}.txt

You should also use [ "$?" -eq 0 ] to avoid the [[ not found error- you haven't mentioned your OS, but you appear not to have bash as /bin/sh. None of this is necessary if you use rsync of course.

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.