How to pass argument in Expect through the command line in a shell script
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?
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:
#!/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
Solution 4:
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.