Reputation: 2043
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
Upvotes: 0
Views: 1042
Reputation: 908
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)
Upvotes: 1
Reputation: 14975
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.
Upvotes: 2