0

I need the return code of the command that is executed over a remote ssh.

result=$(ssh $TARGET_USER@$TARGET_SERVER \
'cp /tmp/test1.txt \
/tmp1/test2.txt')

when the above command is unsuccessful

I want to perform some alerting action.

But the output of the result variable seems to be always null

any ideas how do i make use of the result variable

When i execute the above command i get this

cp: cannot create regular file ‘/tmp1/test2.txt’: No such file or directory

jhon.smith
  • 1,963
  • 6
  • 30
  • 56
  • 1
    Is it always null, even when it succeeds? If this is correct, perhaps you will need to capture `stderr` into the variable instead of `stdout`... – SebasSBM Dec 19 '18 at 09:42
  • `result=$(ssh $TARGET_USER@$TARGET_SERVER 'cp /tmp/test1.txt /tmp1/test2.txt >/dev/null ; printf $?')`? – Biffen Dec 19 '18 at 09:57
  • @SebasSBM yes its always null no matter what if it succeeds or fails – jhon.smith Dec 19 '18 at 12:51
  • Wow Biffen I will try that tomorrow first thing that's a neat trick of adding $?.Wish you would make that as an answer instead of a comment – jhon.smith Dec 19 '18 at 12:53

2 Answers2

2

Just check the exit code:

result=$(ssh $TARGET_USER@$TARGET_SERVER 'cp /tmp/test1.txt /tmp1/test2.txt' 2>/dev/null)

[[ $? -ne 0 ]] && your_error_flow

From man ssh:

 ssh exits with the exit status of the remote command or with 255 if an error
 occurred.
Juan Diego Godoy Robles
  • 14,447
  • 2
  • 38
  • 52
1

I haven't tested it, but this is worth giving it a try:

result=$(ssh $TARGET_USER@$TARGET_SERVER \
'cp /tmp/test1.txt \
/tmp1/test2.txt 2>&1 > /dev/null')

This answer here explained how to capture stderr into a variable. I just applied it to your command (I considered stdout was unnecessary for this)

If it works as expected, the "no such file or directory" error you mentioned will be captured into this variable. Thus, you would have a differentiable value that might allow your code "know" if command was successful or not (stderr would be empty if command was successfull, in theory)

SebasSBM
  • 860
  • 2
  • 8
  • 32