How to pass argument in Expect through the command line in a shell script
111,143
Solution 1
If you want to read from arguments, you can achieve this simply by
set username [lindex $argv 0];
set password [lindex $argv 1];
And print it
send_user "$username $password"
That script will print
$ ./test.exp user1 pass1
user1 pass1
You can use Debug mode
$ ./test.exp -d user1 pass1
Solution 2
A better way might be this:
lassign $argv arg1 arg2 arg3
However, your method should work as well. Check that arg1
is retrieved. For example, with send_user "arg1: $arg1\n"
.
Solution 3
I like the answer provided with this guide.
It creates a parse argument process.
#process to parse command line arguments into OPTS array
proc parseargs {argc argv} {
global OPTS
foreach {key val} $argv {
switch -exact -- $key {
"-username" { set OPTS(username) $val }
"-password" { set OPTS(password) $val }
}
}
}
parseargs $argc $argv
#print out parsed username and password arguments
puts -nonewline "username: $OPTS(username) password: $OPTS(password)"
The above is just a snippet. It's important to read through the guide in full and add sufficient user argument checks.
Solution 4
#!/usr/bin/expect
set username [lindex $argv 0]
set password [lindex $argv 1]
log_file -a "/tmp/expect.log"
set timeout 600
spawn /anyscript.sh
expect "username: " { send "$username\r" }
expect "password: " { send "$password\r" }
interact
Author by
lk121
Updated on July 05, 2022Comments
-
lk121 almost 2 years
I am passing argument in Expect through the command line in a shell script.
I tried this
#!/usr/bin/expect -f set arg1 [lindex $argv 0] spawn lockdis -p expect "password:" {send "$arg1\r"} expect "password:" {send "$arg1\r"} expect "$ "
But it's not working. How can I fix it?
-
joebeeson over 8 yearsWhile this works, be careful using it as your process will appear with the arguments, username and password, when doing something like "ps aux"
-
Vivek over 6 yearscan we loop the argument list and put them in array?
-
Timo about 6 yearsThe expect script is missing
-
eulerworks almost 6 yearsIt isn’t, “missing” it works the same way for any expect script that would be called via bash. Though in this example it would need to be called, “exp.expect.” There was no need for a downvote, my answer explains how to handle what was in question.
-
Timo almost 6 yearsok, I
expect
ed the content of your script which references the parameters from outside as the others showed in their examples. -
spbnick over 5 yearsThe code above is for TCL which
expect
is using, and doesn't make sense for Bash. -
Sohail Si about 2 yearsI like argument checking all the time
-
Han Zhang about 2 yearsThat's why you should pass it a file where your username and password are kept privately.