1

I am having troubles writing an expect script. I want to do something equivalent to the following bash instruction:

iplist=$(cat iplist.txt)

I've tried using set in all the ways that I know but it is still not working. Is there another way or is just that I'm not using it the right way?

set iplist=$(cat iplist.txt)
  • 1
    @don_crissti. Perfect! Sorry about that! I rolled it back ;-) – user88036 Sep 21 '18 at 15:51
  • take a look at sexpect with which you can write Expect scripts with shell code only. – pynexj Sep 22 '18 at 0:33
2

TCL can read(n) a file directly; this is both more efficient and more portable than forking out to some command.

#!/usr/bin/env expect

proc slurp {file} {
    set fh [open $file r]
    set ret [read $fh]
    close $fh
    return $ret
}

set iplist [slurp iplist.txt]

puts -nonewline $iplist

This also (if necessary) allows various open(n) or chan configure options to be specified, for example to set the encoding:

#!/usr/bin/env expect

package require Tcl 8.5

proc slurp {file {enc utf-8}} {
    set fh [open $file r]
    chan configure $fh -encoding $enc
    set ret [read $fh]
    close $fh
    return $ret
}

set data [slurp [lindex $argv 0] shiftjis]

chan configure stdout -encoding utf-8
puts $data

Which if saved as readfile and given somefile as input:

% file somefile
somefile: DBase 3 data file with memo(s) (1317233283 records)
% xxd somefile
00000000: 8365 8342 8362 834e 838b                 .e.B.b.N..
% ./readfile somefile
ティックル
% 
  • You're leaking file descriptors. You should close the file in the slurp proc. – glenn jackman Sep 21 '18 at 19:44
0

Thanks for your answers, I've just found the solution in another post, in the function set the only missing was "exec", resulting the line:

set iplist [exec cat /root/iplist.txt]

And the expect file is going well, without any troubles!

  • If this is the solution, please mark it as such by clicking the ✔ to the left of this answer to indicate this. Welcome to U&L! – DopeGhoti Sep 21 '18 at 16:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.