Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

shell - expect script error $argv not found

I have the following shell(/expect) script.

#!/bin/bash
expect -c '
set user [lindex $argv 0]
set password [lindex $argv 1]
set ipaddr [lindex $argv 2]
set timeout 10
spawn ssh $user@$ipaddr mkdir -p ~/Tested
expect "*?assword:*"
send -- "$password
"
interact
'

when I run the script as follows

. test.sh abcd test 10.xx.xxx.xxx

It gives the following error

can't read "argv": no such variable
    while executing
"lindex $argv 0"
    invoked from within
"set user [lindex $argv 0]"

Does anybody know what the error is , if I replace [lindex $argv 0] lines with actual value the script runs.

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The -c flag in expect provides a way of executing commands specified on the command line rather than in a script.

In general, -c is flag is used in command line used to execute commands before a script takes control.

They are used as below.

expect -c "set debug 1" myscript.exp

Inside myscript.exp, you can check the value of this variable:

if [info exists debug] {
 puts "debugging mode: on"
}
else {
 set debug 0
 # imagine more commands here
 if $debug {puts "value of x = $x"}
}

When the script is run, it checks if debug is defined by evaluating info exists, a Tcl command which returns 1 if the variable is defined or 0 if it is not. If it is defined, the script can then test it later to determine if it should print debugging information internal to the script. The else clause sets debug to 0 just so that later a simple if $debug test can be used.

Now, lets come to your question. You are using the variable argv which is the command line argument list passed to some script and with -c flag in use, you cant make use of it since argv is intended to be used inside a script, not outside.

Instead of doing this way, you can put your code inside a script file and call the code as below.

expect yourscript.exp username pwd ip_address

If you still interested in command line arguments, then you can try what fwilson suggested in comments.

expect yourscript.exp $1 $2 $3

With this, yourscript.exp will get the arguments from the shell script.

Reference : Exploring Expect


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...