bash function with ssh

6,792

Solution 1

You could use here-documents:

ssh user@serveraddress <<"END"
dbuser=user
dbpass=pass
DBS=$(mysql -u$dbuser -p$dbpass -Bse 'show databases'| egrep -v 'information_sch$')
for db in $DBS; do
    echo "DB name -  $db"
done
END

See: http://tldp.org/LDP/abs/html/here-docs.html

Solution 2

Can you not just put your script on the remote host and use ssh to run it

ssh [email protected] /path/to/script

Or if your script requires no command line parameters ypu can do this

cat script | ssh [email protected]

EDIT:

After some more research then this is probably a better solution all round

ssh [email protected] 'bash -s' <script 

or

ssh [email protected] 'bash -s' <script param1 param2

If the -s option is present, or if no arguments remain after option processing, then commands are read from the standard input. This option allows the positional parameters to be set when invoking an interactive shell.

Share:
6,792

Related videos on Youtube

imp
Author by

imp

Updated on September 18, 2022

Comments

  • imp
    imp almost 2 years

    I am just getting into bash for the first time.

    How would I run a function on the server in this scope? drush status is something only on the server being ssh connected too.

    #!/bin/bash
    
    function test {
        drush status
    }
    
    function connect {
        ssh user@serveraddress 'test'
    
    }
    
    connect
    

    I understand you need to put the remote code in the ssh user@server 'code here', however complicated things get confused with all the '" etc. For instance this should echo all the db names of the server.

    function connect {
    
    
        ssh user@serveraddress 
       '
    
        dbuser=user
        dbpass=pass
        DBS=`mysql -u$dbuser -p$dbpass -Bse 'show databases'| egrep -v 'information_sch$
        for db in $DBS; do
            echo "DB name -  $db"
        done
    
        '   
    }
    
    
    connect
    

    Any help links appreciated, cheers

  • imp
    imp over 12 years
    thankyou very much there are afterall a few ways to get this done. I know this will come in handy again. To avoid the Pseudo-terminal will not be allocated because stdin is not a terminal. I added a -T to the ssh -T user@serveraddress.