3

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?

0

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

0

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
  • 1
    This is cleaner than export:ing all three but not fundamentally different. – tripleee Apr 20 '17 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. – user218374 Apr 20 '17 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. – tripleee Apr 20 '17 at 7:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.