M
M
MarkThule2020-10-06 11:37:55
linux
MarkThule, 2020-10-06 11:37:55

Bash: how to write command output from HEREDOC to a log file?

There is a main server. It executes a large list of commands using HEREDOC over SSH on a remote server. Each command has an if condition. The result of executing commands on a remote server is logged to a file on the main server. But the problem is that logging works very crookedly. Either it does not work in principle, or if wrapped in a function, it is always executed regardless of the result. How can this be implemented? Or is it possible to implement a similar script without HEREDOC?

Example:

function ssh_connection {
      ssh -T -i <ssh_key> [email protected]
}
log="Failed! $(date)"
log_file=/var/log/log_file
ssh_connection << SCRIPT
          command
          if [ \$? - eq 0 ]
          then
                 echo "Success"
          else
                 echo "Failed"
                 echo $log >> $log_file
          fi
SCRIPT

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Saboteur, 2020-10-06
@saboteur_kiev

ssh -T -i <ssh_key> [email protected] -с 'command && echo "Success" || ( echo "Failed"; echo "Failed! $(date) >> /var/log/log_file'
}

O
Oleg Volkov, 2020-10-08
@voleg4u

I can recommend the logger command for dumping logs directly into messages. Practice has shown that the solution is an ultimatum. You don't even need to rotate. And if everything merges into the central syslog, then you'll get hurt.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question