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 [email protected] '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?

1 Answer 1

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 [email protected] 'cat >> all_lines_collected.txt' &&
   rm some_lines_to_append.txt ||
   echo 'Error occurred.'
5
  • 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
    Commented Jan 26, 2017 at 2:59
  • It seems just cat some_lines_to_append.txt | ssh [email protected] 'cat >> all_lines_collected.txt' && rm some_lines_to_append.txt would just work better then first expected by me...
    – dronus
    Commented Jan 26, 2017 at 3:01
  • 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 [email protected] 'cat >> all_lines_collected.txt' && rm some_lines_to_append.txt || echo 'Error occurred' is enough.
    – Alex
    Commented Jan 26, 2017 at 5:11
  • I edited my answer so it should reflect your particular needs without extra unnecessary information.
    – Alex
    Commented Jan 26, 2017 at 17:29
  • Cool. Sometimes, the first shot is working well despite the expectation.
    – dronus
    Commented Feb 8, 2017 at 0:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .