Search code examples
bashssh

How can I use variables for options of ssh


I want to use this compound ssh command:

o1='"NumberOfPasswordPrompts=0"'
o2='"NumberOfPasswordPrompts=1"'
o3='"ConnectTimeout=100"'

x=`sshpass -p "$psw" ssh -q -o $o2 -o $o3 2>/dev/null $usr@$srv <<ZZZ
     ### some command e.g.:
     sudo -u oracle -i
     export LANG=en_US.UTF-8
     ORACLE_HOME=$home
     export ORACLE_HOME   # export ORACLE_BASE ORACLE_HOME
     PATH=\\$ORACLE_HOME/bin:\\$PATH
     \\$ORACLE_HOME/OPatch/opatch lsinv
ZZZ`

it doesn't work, it seems that the bash interpreter can't understand the options of ssh because when I write the options directly then everything is OK:

x=`sshpass -p "$psw" ssh -q -o "NumberOfPasswordPrompts=1" -o "ConnectTimeout=100" 2>/dev/null $usr@$srv <<ZZZ
     ### some command e.g.:
     sudo -u oracle -i
     export LANG=en_US.UTF-8
     ORACLE_HOME=$home
     export ORACLE_HOME   # export ORACLE_BASE ORACLE_HOME
     PATH=\\$ORACLE_HOME/bin:\\$PATH
     \\$ORACLE_HOME/OPatch/opatch lsinv
ZZZ`

I need to use more and alternate options of ssh according to different conditions with the same 'here document'. So I would like to calculate them and put into variables before using them in ssh.I tried to use the eval command but it didn't succeed.How could I put the options into variables ?


Solution

  • Many thanks to @Fravadone for shedding light on the root of the problem. I mistakenly thought that I needed to use the " symbol when specifying SSH options. That's why I wrote, for example: o1='"NumberOfPasswordPrompts=0"' The correct syntax is:

    o1=NumberOfPasswordPrompts=0
    o2=NumberOfPasswordPrompts=1
    o3=ConnectTimeout=100
    
    x=`sshpass -p "$psw" ssh -q -o $o2 -o $o3 2>/dev/null $usr@$srv <<ZZZ
     ### some command e.g.:
     sudo -u oracle -i
     export LANG=en_US.UTF-8
     ORACLE_HOME=$home
     export ORACLE_HOME   # export ORACLE_BASE ORACLE_HOME
     PATH=\\$ORACLE_HOME/bin:\\$PATH
     \\$ORACLE_HOME/OPatch/opatch lsinv
    ZZZ`
    

    It also works without the = sign, though it isn't documented. In this case, of course I have to use the " symbol.

    o1="NumberOfPasswordPrompts 0"
    o2="NumberOfPasswordPrompts 1"
    o3="ConnectTimeout 100"
    
    x=`sshpass -p "$psw" ssh -q -o "$o2" -o "$o3" 2>/dev/null $usr@$srv <<ZZZ
     ### some command e.g.:
     sudo -u oracle -i
     export LANG=en_US.UTF-8
     ORACLE_HOME=$home
     export ORACLE_HOME   # export ORACLE_BASE ORACLE_HOME
     PATH=\\$ORACLE_HOME/bin:\\$PATH
     \\$ORACLE_HOME/OPatch/opatch lsinv
    ZZZ`