Devon Ville
Devon Ville

Reputation: 2091

Use the same command in shell script, just with a prefix

I have a command I run to check if a certain db exists.
I want to do it locally and via ssh on a remote server.
The command is as so:

mysqlshow -uroot | grep -o $DB_NAME

My question is if I can use the same command for 2 variables,
the only difference being ssh <remote-server> before one?
Something along the lines of !! variable expansion in the CLI:

LOCAL_DB=mysqlshow -uroot | grep -o $DB_NAME
REMOTE_DB=ssh <remote-host> !!

Upvotes: 0

Views: 274

Answers (2)

PradyJord
PradyJord

Reputation: 2160

You can create a function in .bashrc something like:

function showrdb() {  
   ssh remote@host "$1" 
}  
export -f showrdb

and then source .bashrc and call the function like;

showrdb "command you want to run on remote host"

Or alternately you can create a shell script contains the same function(or only the ssh line) and call the script as

./scriptname "command to execute of remote host"

But the level of comfort for me is more in first approach.

Upvotes: 0

Pavel
Pavel

Reputation: 7552

something like this perhaps?

cmd="whoami"
eval $cmd
ssh remote@host $cmd

eval will run the command in the string $cmd locally

also, for checking tables, it's safer to ask for the table name explicitly via a query

SHOW TABLES LIKE 'yourtable';

and for databases:

SHOW DATABASES LIKE 'yourdb';

Upvotes: 1

Related Questions