Newstein
Newstein

Reputation: 141

How to use a source file while executing a script on a remote machine over SSH

I am running a bash script on a remote machine over SSH.

ssh -T $DBHOST2 'bash -s' < $DIR/script.sh <arguments>

Within the script I am using a source file for defining functions used in the script script.sh.

DIR=`dirname $0`      # to get the location where the script is located
echo "Directory is $DIR"
. $DIR/source.bashrc  # source file 

But since the source file is not present in the remote machine it results in an error.

Directory is .
./source.bashrc: No such file or directory

I can always define the functions along with the main script rather than using a source file, but I was wondering is there any way to use a separate source file.

Edit : Neither the source file nor the script is located in the remote machine.

Upvotes: 1

Views: 2433

Answers (3)

sborsky
sborsky

Reputation: 561

Here are to ways to this - both only requiring one ssh session.

Option 1: Use tar to copy your scripts to the server

tar cf - $DIR/script.sh $DIR/source.bashrc | ssh $DBHOST2 "tar xf -; bash $DIR/script.sh <arguments>"

This 'copies' your scripts to your $DBHOST2 and executes them there.

Option 2: Use bashpp to include all code in one script

If copying files onto $DBHOST2 is not an option, use bashpp.

Replace your . calls with #include and then run it through bashpp:

bashpp $DIR/script.sh | ssh $DBHOST2 bash -s

Upvotes: 3

Newstein
Newstein

Reputation: 141

The following acheives what I am trying to do.

1.Copy the source file to remote machine.

scp $DIR/source.bashrc $DBHOST2:./

2.Execute the local script with arguments on the remote machine via SSH

ssh $DBHOST2 "bash -s" -- < $DIR/script.sh <arguments>

3. Copy remote logfile logfile.log to local file dbhost2.log and remove the source file and logfile from the remote machine

ssh $DBHOST2 "cat logfile.log; rm -f source.bashrc logfile.log" > dbhost.log

Upvotes: 0

Ipor Sircer
Ipor Sircer

Reputation: 3141

ssh -T $DBHOST2 'bash -s' <<< $(cat source_file $DIR/script.sh)

Upvotes: 0

Related Questions