Expect script reading commands from file

2019-08-06 09:30发布

问题:

I'm trying to write an expect script that reads commands from a file and executes them, as explained in this topic. Here is my script called script.sh:

#!/usr/bin/expect

set f [open "script_cmds.txt"]
set cmds [split [read $f] "\n"]
close $f

foreach cmd $cmds {
    spawn cmd 
}

expect eof
close

And the file script_cmds.txt, situated in the same folder, looks like this:

mkdir cmdlisttest1
mkdir cmdlisttest2

To compile and run the script on cygwin I use

chmod +x script.sh
d2u script.sh
./script.sh

The output I get reads

spawn cmd
spawn cmd
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\cygwin\home\user>

and then it stops there without exiting. The folders cmdlisttest1 and cmdlisttest2 are not created.

I'm fairly new to expect scripts; can anyone spot the mistake(s)?

回答1:

You're executing spawn cmd instead of spawn $cmd.
With $cmd you're reading the value stored in the variable cmd and that's what you want.