Monday, October 25, 2021

[SOLVED] Bash, command on remote server returns true in case of failed

Issue

Command executed on remote server returns true even if failed. Here is the code.

command="
sudo su - postgres -c 'pg_dump -Fc ${var[1]}'
"

if
ssh -n -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no "$username"@"${var[0]}" "$command" > "$folder_export"/"${var[0]}"/"$date"-"$time"-"${var[0]}"-"${var[1]}".dump
export_end=$date-$time
then
export=true
else
export=false
fi

I tried to stop postgres on remote server. Output shows me this.

pg_dump: [archiver (db)] connection to database "coopweb" failed: could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

But if condition returns true. I don't know why. Could be some option in ssh command wrong? Or where is the problem?

Thank you.


Solution

In your statement the return code evaluated in the if expression is the return code of the assignment to the variable export_end. One solution would be to move this assignment into the if/else branches:

 ...
 if ssh -n -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no "$username"@"${var[0]}" "$command" > "$folder_export"/"${var[0]}"/"$date"-"$time"-"${var[0]}"-"${var[1]}".dump
 then
   export_end=$date-$time
   export=true
 else
   export_end=$date-$time
   export=false
 fi


Answered By - mirus