2

I'm trying to write an expect script (for the first time) and what I'm trying to do is read lines from a text file (input.txt) and assign them as specific variables in an expect script. My text file takes input from a web app and will have exactly 5 lines (5 variables for my script). Since I already know what each line represents, I want to create specifically-named variables for them..

line 1 is $user

line 2 is $password

line 3 is $logs1

line 4 is $logs2

line 5 is $containerName

I've looked at this link: Read file into String and do a loop in Expect Script and see that they used

    set f [open "host.txt"]
    set hosts [split [read $f] "\n"]
    close $f

to collect from a file of all host names and just iterate through them in a loop but how do I name each line differently according to what the line represents?

E tom
  • 117
  • 2
  • 9

2 Answers2

2

The most straightforward method is just:

set f [open "host.txt"]
gets $f user
gets $f password
gets $f logs1
gets $f logs2
gets $f containerName
close $f

For more background see https://www.tcl.tk/man/tcl8.5/tutorial/Tcl24.html

Colin Macleod
  • 4,222
  • 18
  • 21
  • An alternative to 5 gets commands is `lassign [split [read -nonewline $f] \n] user password logs1 logs2 containerName` – glenn jackman May 18 '18 at 20:05
  • Well if you want to be minimalist you could compress the 5 gets commands into `foreach v {user password logs1 logs2 containerName} {gets $f $v}` but for the OP I suspect simple and straightforward is best. – Colin Macleod May 21 '18 at 08:19
1

In your example, hosts is a list of items. You access the individual items using the lindex command. Example:

set user [lindex $hosts 0]
set passwd [lindex $hosts 1]
user1934428
  • 19,864
  • 7
  • 42
  • 87