This is a continuation of this topic; since it's a different question from the OP I'm making a new topic. I have an expect script I can't get working that is supposed to read commands from a file and execute them. This is the script itself, called script.sh
:
#!/usr/bin/expect
set prompt {\$\s*$}
set f [open "script_cmds_u.txt"]
set cmds [split [read $f] "\n"]
close $f
foreach cmd $cmds {
spawn $cmd
expect -re $prompt
}
expect eof
close
The file script_cmds.txt looks like this:
mkdir cmdlisttest1
mkdir cmdlisttest2
To run the script I use
tr -d '\r' < testpswd2.sh > testpswd2_u.sh
tr -d '\r' < script_cmds.txt > script_cmds_u.txt
chmod +x testpswd2_u.sh
./testpswd2_u.sh
Doing it like this I get the following error: couldn't execute "mkdir cmdlisttest1": no such file or directory
.
So I try a number of changes:
- Change it to
send $cmd
in the loop. This changes the output tomkdir cmdlisttest1couldn't compile regular expression pattern: invalid escape \ sequence
. I also try this with\n
and\r
after the commands inscript_cmds.txt
. - Remove the
expect -re $prompt
in the loop. Then I getmkdir cmdlisttest1mkdir cmdlisttest2
and it hangs there. Put a
spawn "\n"
after thesend $cmd
; then I getmkdir cmdlisttest1spawn
couldn't execute "
": no such file or directory
The error is due to
spawn
is taking the whole string (e.g.:mkdir cmdlisttest1
) as a command without arguments.Try instead with argument expansion (thanks @glenn jackman):
Another option:
With
[lindex $cmd 0]
you'll get mkdir;With
[lrange $cmd 1 [llength $cmd]]
, the arguments (e.g. cmdlisttest1).