Export Bash command-line-argument variables for use in embedded Expect

bash, command-line-arguments, expect, variables

Solution

Code with nesting quotes is not easy to write and read. I recommend you use the shell's here-document syntax. For example (demo'ing 2 ways of passing `bash` vars to `expect`):

$ cat foo.sh
arg1=$1
export arg2=$2

expect << END
puts $arg1
puts \$env(arg2)
END
$ bash foo.sh hello world
hello
world
$

I prefer `export var` from the shell and reference it with `$env(var)` in expect as you'll not have to worry about if the `var` has some special chars (like `'`, `"` or spaces) in it.

Problem

The `echo` test shows me my command line variables are working, but how do I pass them, export them, to be used in an embedded `expect`? ``` #!/bin/bash echo name of script is $0 echo host is $1 echo hostusername is $2 echo hostpassword is $3 expect -c 'spawn ssh -l $2 $1 < ./sf-wall_scp_bash.sh sleep 2 expect { "(yes/no)? " {send "yes\n"} exp_continue } expect { "?assword" {send "$3\r"} } sleep 1 ' ``` If invoked with the `expect` shebang, it works like ``` #!/usr/bin/expect set host [lindex $argv 0] set hostusername [lindex $argv 1] set hostpassword [lindex $argv 2] spawn ssh -l $hostusername $host sleep 2 expect { "(yes/no)? " {send "yes\n"} exp_continue } expect { "?assword" {send "$hostpassword\r"} } sleep 1 ``` ...which works as expected. I need to use `bash` though and embed `expect` because the script is needing to call bash specific commands, functions, built in variables...otherwise simply using the second example would be a working option, but it is not. I've tried declaring and exporting the command line argument variables, and changing $1, $2, $3 in the first example above respectively to the variable names declared and exported, which works in another script I have in which I am actually declaring the variables within the script...the difference being they are not command line arguments. ``` host=$1 export host hostusername=$2 export hostusername hostpassword=$3 export hostpassword ``` as well as just exporting them ``` export host export hostusername export hostpassword ``` and attempting the first example above. No change, `expect` continues to claim can't read "X": no such variable In another bash script I was able to successfully export variables by BOTH declaring them and then exporting them as in the example above. But I have not been able to have any such luck with passing `bash` command line argument variables to `expect`

Original source