-1

Im writing a script the i add later as a cronjob, so this script has functions and inside it uses a here document to execute commands on remote server

there is a variabe "result" in this script that will tel the state of the hosts

I need the same variable "result" to echo outside of the here document (EOF)

How do i do this

one(){
ssh_cmd="$(cat <<-EOF

        echo --------------------------------------------------------------
        echo "Checking testapp Status on Domain Controller --> host = slave1 "
        echo --------------------------------------------------------------

        result=(\$(/opt/jboss/web/bin/jboss-cli.sh --connect controller=10.0.0.4:9990 --commands='ls /host=slave1/server-config=testapp' | grep 'status=' | awk 'FNR%2' | sed -r 's/.{7}//'))

        echo ----------------
        echo "\${result[@]}"
        echo ----------------

        if [ "\${result[@]}" != "STARTED" ];
        then
                echo --------------------------------------
                echo "Starting the server"
                echo --------------------------------------

                /opt/jboss/web/bin/jboss-cli.sh --connect controller=10.0.0.4:9990 --commands='/host=slave1/server-config=testapp:start'
        else
                echo --------------------------------------
                echo "Server is running"
                echo --------------------------------------
        fi

EOF
)"
ssh -t root@someserver "$ssh_cmd"
}

echo $result

if [ $result == value];
then
  two (run function two)
else
exit

1 Answers1

0

need the same variable "result" to echo outside of the here document (EOF)

Then you need to send it, no other way. You could send it using the output of ssh:

     ....
     # output the value.
     echo "unique_string_with_result=$result"
EOF
)"
    # get ssh output to a file
    ssh ..... | tee tempfile.txt
    # filter the output and extract the value
    result=$(sed -n 's/unique_string_with_result=//p' tempfile.txt)
}
KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • I thought so, was hoping there was some way to do it without creating a file on the remote server, but thank you. – Ashwin Adams Sep 09 '21 at 15:55
  • `without creating a file on the remote server` The code I presented above does not create a file on the remove server. It creates a file on the local workstation. Still, you can use a `var=$(ssh .... | tee /dev/stderr);` variable as a temporary location of output, with proper `tee` redirection. – KamilCuk Sep 09 '21 at 15:57
  • 1
    Thanks i misunderstood :) – Ashwin Adams Sep 09 '21 at 16:02