Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass variables from a shell script to an expect script?

Tags:

bash

shell

expect

I've shell script as below:

#!/bin/bash

echo "Select the Gateway Server:"
echo "   1. Gateway 1"
echo "   2. Gateway 2"
echo "   3. Gateway 3"

read gatewayHost

case $gatewayHost in
    1) gateway="abc.com" ;;
    2) gateway="pqr.com" ;;
    3) gateway="xyz.com" ;;
    *) echo "Invalid choice" ;;
esac

/mypath/abc

In above script, I'm fetching gateway from user input selection & trying to pass to my abc.sh script which is expect scriptshown below:

#!/usr/bin/expect

set timeout 3
spawn ssh "james@$gateway"
expect "password:"
send "TSfdsHhtfs\r";
interact

But I'm not able to pass gateway variable from shell script to expect script. Can any one tell me how to achieve this?? Please note that I need to use shell script only due to legacy reasons (Cannot use tcl script or can't do everything in expect script itself)

like image 781
Freephone Panwal Avatar asked Mar 15 '13 00:03

Freephone Panwal


People also ask

How do you pass a variable to a function in shell script?

Syntax for defining functions: To invoke a function, simply use the function name as a command. To pass parameters to the function, add space-separated arguments like other commands. The passed parameters can be accessed inside the function using the standard positional variables i.e. $0, $1, $2, $3, etc.

What does $() mean in shell script?

$() – the command substitution. ${} – the parameter substitution/variable expansion.

What is $_ in shell script?

The “$_” special variable can even be used for displaying the path of a Bash script in Ubuntu 20.04. It can do so if you create a simple Bash script and use the “$_” special variable before writing any other command in your Bash script. By doing so, you will be able to get the path of your Bash script very easily.


1 Answers

From your shell script:

/mypath/abc $gateway

From your expect script:

#!/usr/bin/expect

set gateway [lindex $argv 0]; # Grab the first command line parameter

set timeout 3
spawn ssh "james@$gateway"
expect "password:"
send "TSfdsHhtfs\r";
interact
like image 165
Hai Vu Avatar answered Sep 24 '22 05:09

Hai Vu