Hints On The spawn Command
I made one other change to the script that is worth noting. The first script only accepted a single argument as a program name. But this new version of maxtime understands that additional arguments after the program name are arguments to the program. This is accomplished with the command:
eval spawn [lrange $argv 1 end]
The lrange extracts all but the first argument (the timeout) and returns a list where the first element is the program name and the remaining elements are the arguments to the program. Assuming lrange produces "sleep 5“, eval joins that to spawn ending up with:
spawn sleep 5
eval executes this as if it were the original command line. Compare the eval command with the following:
spawn [lrange $argv 1 end] ;# WRONG!
In this case, spawn takes the result of lrange as a program name and tries to run that program. Again, the result of lrange is "sleep 5“, and this entire string is then used as the program name. Needless to say, there is no program by the name "sleep 5“.
It is worth remembering the command "eval spawn [lrange $argv ... end]“. It is handy for writing scripts that allow optional command-line arguments to be passed in to become the arguments to the spawned process. This command or a variation of it appears in many of the later examples in this book.
Here is the production version of the maxtime script:
#!/usr/local/bin/expect -- set timeout [lindex $argv 0] eval spawn [lrange $argv 1 end] expect
One other precautionary note about ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access