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?

Uwe Keim
  • 2,420
  • 5
  • 30
  • 47
  • `[[` is a `bash` syntax, but you seem to be running under a different shell. – choroba Jan 08 '21 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 08 '21 at 17:40
  • Don't include code into comments. You can update the question with additional information. – choroba Jan 08 '21 at 18:00
  • Also, you probably want to `rm` the local file, not the remote one, right? – choroba Jan 08 '21 at 18:01
  • No. Is everything that I run behind `bin/bash < – user611630 Jan 08 '21 at 19:08
  • Ah, you're talking about the code in the comment, I was talking about the original one in the question. I've already commented on the one in the comment. – choroba Jan 08 '21 at 20:14
  • For `${var}` vs `$var`, see [What is the difference between `${var}`, `“$var”`, and `“${var}”` in the Bash shell?](https://stackoverflow.com/questions/18135451/what-is-the-difference-between-var-var-and-var-in-the-bash-shell) – Gordon Davisson Jan 09 '21 at 09:01

1 Answers1

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.

Chris Rees
  • 275
  • 1
  • 7