3

I'm using CentOS linux.

In one line cmd, that returns 0 if success, non-0 if failure, I need:

  1. Transfer a file to a remote server.
  2. Don't transfer the file if filename exists in remote server (return non-0)

I thought about using rsync, but it returns 0 if the filename exists. scp replaces the existing file, so it doesn't help me either.

A twist: The user that performs this command is not root, the files are owned by this user. The destination is owned by same user. There is an ssh trust for root. But not for this user. Can't be prompted for password, because this command is part of an automatic script. Preliminary configuration steps are possible. I can add them as a one time configuration. Can anyone help?

1

Here's a simple way that doesn't preserve metadata:

ssh server.example.com 'set -C; cat >/path/to/remote/file' </path/to/local/file

You can do it with rsync with the right options. The return code will be 0 if the file exists, but you can find out from the verbose output instead.

changes=$(rsync -a --ignore-existing --itemize-changes \
                /path/to/local/file server.example.com:/path/to/remote/file)
if [ $? -ne 0 ]; then
  echo >&2 "Some error occured"
  return 2
elif [ -n "$changes" ]; then
  echo "The file was copied"
  return 0
else
  echo "The file already existed"
  return 1
fi
-1

Check if the file exists on the remote host first:

if ! ssh remotehost [ -f incoming/DB1026910.sql ]; then
    scp DB1026910.sql remotehost:incoming/
fi
2
  • 1
    What if the file is created in the meantime? Perhaps even more crucially, what if there is some other error in the first connection?
    – mattdm
    Jul 21 '14 at 16:24
  • A one-liner would be something like "ssh remotehost test ! -f /tmp/filename && scp /tmp/filename remotehost:/tmp/". It requires 2 sessions, which i would like to avoid, and it fails under the listed above reasons
    – csny
    Jul 21 '14 at 16:38

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.