Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign local variable with a remote command result in bash script?

Tags:

bash

shell

ssh

I'm writing a script to restore Master-Slave replication on a set of servers. Lost in bash syntax trying to assign a local variable with a result of a remotely ran command substitution with local values:

function doRemote() {
    ssh s1.domain.com   <<ENDSSH
        mysql -u root -pXXX --execute="DROP DATABASE db; CREATE DATABASE db;"
        mysql -u root -pXXX --database=db < $WORKDIR$FILENAME
        sudo rm -rf /var/log/mysql/db-bin.*
        mysql -u root -pXXX --execute="FLUSH LOGS;"
        CURRENT_LOG=`mysql -u root -pXXX --execute="SHOW MASTER STATUS" -AN | awk '{print $1}'`
        CURRENT_POS=`mysql -u root -pXXX --execute="SHOW MASTER STATUS" -AN | awk '{print $2}'`
        # ...
ENDSSH
}

The two lines assigning CURRENT_* variables are the problem: the mysql -u... command gets executed locally, instead of remote session.

Please advice how to run that remotely, assigning the local variable with a result of a remote mysql command.

like image 536
Serge Avatar asked Jan 15 '14 16:01

Serge


People also ask

How do you assign the output of a command to a variable in Linux?

To store the output of a command in a variable, you can use the shell command substitution feature in the forms below: variable_name=$(command) variable_name=$(command [option ...] arg1 arg2 ...) OR variable_name='command' variable_name='command [option ...]

How do I assign a variable to a variable in bash?

To assign the value associated with the variable dest to the variable source , you need simply run dest=$source .


2 Answers

Try escaping ENDSSH as shown below, so that variable evaluation occurs on the remote host:

ssh s1.domain.com <<\ENDSSH
    # ...
ENDSSH
like image 101
dogbane Avatar answered Nov 12 '22 07:11

dogbane


Try escaping your calls for cmd-substitution

CURRENT_LOG=`mysql -u root -pXXX --execute="SHOW MASTER STATUS" -AN | awk '{print $1}'`

now is

CURRENT_LOG=\`mysql -u root -pXXX --execute="SHOW MASTER STATUS" -AN | awk '{print $1}'\`

or join the 90's ;-) and use the $( ... ) form of cmd substitution (escaped also)

CURRENT_LOG=\$(mysql -u root -pXXX --execute="SHOW MASTER STATUS" -AN | awk '{print $1}' )

You might have to use more than one '\' char to get proper escaping.

IHTH

like image 2
shellter Avatar answered Nov 12 '22 07:11

shellter