4

I am trying to execute the script file sc.sh on remote machine user@remote-01 using ssh. I also need to pass the arguments while executing this ssh command. So that i have to use those arguments in sc.sh. This is my script which I am trying to execute

    var1=True
    var2=False
    var3=True

    sshpass -p 'pswd' ssh user@remote-01 "bash -s" < /home/user/sc.sh

My sc.sh looks like:

    if var1 -eq True; then
       echo "Todo"
    fi

    if var2 -eq True; then
       echo "Todo"
    fi

    if var3 -eq True; then
       echo "Todo"
    fi

    ..... so on

How can i pass var1, var2, var3 as arguments and use them in my script as above?

3 Answers 3

2

This has previously been answered in question.

however what you would want to probably do will be something like the following.

sc.sh

#!/bin/bash

var1=$1
var2=$2
var3=$3

if $var1 -eq True; then
   echo "Todo1"
fi

if $var2 -eq True; then
   echo "Todo2"
fi

if $var3 -eq True; then
   echo "Todo3"
fi

then run the following command

ssh user@remote-01 'bash -s' < test.sh true true true

arguments in BASH can be referenced by $number e.g. $1

1

Finally, got the solution by trying many trial and error attempts.

 var1="True"
 var2="False"
 var3="True"

 sshpass -p 'pswd' ssh user@remote-01 "bash -s" < /home/user/sc.sh "$var1 $var2 $var3"

And should use as follows in sc.sh

if [ "$1" = "True" ]; then
   echo "Todo"
fi
if [ "$2" = "False" ]; then
   echo "Todo"
fi
if [ "$3" = "True" ]; then
   echo "Todo"
fi
0

Here we pass the variables var1/var2/var3 as env variables on the ssh command line which then become available to the bash code on the remote m/c.

var1="$var1" var2="$var2" var3="$var3" \
   sshpass -p 'pswd' ssh user@remote-01 "bash -s" < /home/user/sc.sh

The contents of sc.sh will be:

if [ "$var1" = True ]; then
   echo "Todo"
fi

if [ "$var2" = True ]; then
   echo "Todo"
fi

if [ "$var3" = True ]; then
   echo "Todo"
fi

..... so on
3
  • 1
    This is cleaner than export:ing all three but not fundamentally different. Commented Apr 20, 2017 at 7:41
  • The difference lies in the fact that these are locally global to the ssh and it's children. The rest of the code don't have a clue about them and that's the difference compared to blanket export-ing. Commented Apr 20, 2017 at 7:53
  • "locally global"? (-: Yeah, just pointing out that both would work, and if the OP's script is small, it might be a simpler change to just export the variables. Commented Apr 20, 2017 at 7:55

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.