2

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

user9517
  • 114,104
  • 20
  • 206
  • 289
imp
  • 123
  • 1
  • 5

3 Answers3

5

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

Mircea Vutcovici
  • 16,706
  • 4
  • 52
  • 80
  • 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`. – imp Dec 23 '11 at 14:49
2

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

ssh user@remote.tld /path/to/script

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

cat script | ssh user@remote.tld

EDIT:

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

ssh user@remote.tld 'bash -s' <script 

or

ssh user@remote.tld '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.

user9517
  • 114,104
  • 20
  • 206
  • 289
0

another way...

function connect {

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

}

In other words: Only run the most necessary code on the remote machine, the rest local. Or - don't use backticks at all:

function connect {

    dbuser=user
    dbpass=pass
    ssh user@serveraddress "mysql -u$dbuser -p$dbpass -Bse 'show databases'" \
    |egrep -v 'information_sch$' \
    |while read db; do
        echo "DB name -  $db"
    done

}
sborsky
  • 305
  • 1
  • 6