Check success of remote file append via ssh

0

I like to periodically append some data to a remote file via ssh and remove it locally. Like:

cat some_lines_to_append.txt | ssh user@example.com 'cat >> all_lines_collected.txt'
rm some_lines_to_append.txt

Now I like to make sure some_lines_to_append.txt is only removed, if the lines where successfully transfered. How to do that?

Does >> create some sort of error return code by itself on failure, or does cat in this case, and will ssh deliver that return code?

Will shh itself deliver non-zero return codes in any occasion that it was finished prematurely?

dronus

Posted 2017-01-24T23:34:51.070

Reputation: 1 482

Answers

1

cat will return 0 (zero) on success.

According to ssh manual :

EXIT STATUS

  ssh exits with the exit status of the remote command or with 255 if an error occurred.

So, in your case it is enough

cat some_lines_to_append.txt |
   ssh user@example.com 'cat >> all_lines_collected.txt' &&
   rm some_lines_to_append.txt ||
   echo 'Error occurred.'

Alex

Posted 2017-01-24T23:34:51.070

Reputation: 5 606

Cool. Also someone else told me ssh would in fact pass the return code of the invoked commands. So maybe the pipe would just work without capturing the return code via echo $?and rc=...? – dronus – 2017-01-26T02:59:42.723

It seems just cat some_lines_to_append.txt | ssh user@example.com 'cat >> all_lines_collected.txt' && rm some_lines_to_append.txt would just work better then first expected by me... – dronus – 2017-01-26T03:01:08.157

Yes, ssh exits with the exit status of the remote command or with 255 if an error occurred. rc=$(... code needed when more complex remote commands executed and you want to catch some errors in a middle, but in your case cat some_lines_to_append.txt | ssh user@example.com 'cat >> all_lines_collected.txt' && rm some_lines_to_append.txt || echo 'Error occurred' is enough. – Alex – 2017-01-26T05:11:53.263

I edited my answer so it should reflect your particular needs without extra unnecessary information. – Alex – 2017-01-26T17:29:40.923

Cool. Sometimes, the first shot is working well despite the expectation. – dronus – 2017-02-08T00:14:02.370