2

I can't get to have the variables in an expect loop written:

#!/bin/bash

expect -c "
set var1 10
puts {$var1}
puts $expect_out({$var1})

foreach name { bob jim jacobo henric } {
   puts {hello $name $var1}  
}"

my output is:

# ./test 
({})
hello  
hello  
hello  
hello

So basically it's not expanding any variable. Any idea?

5 Answers 5

2

You should quote with ', not "! This should get the job done:

#!/bin/bash

expect -c '
    set var1 10
    puts "$var1"

    send_user "Confirm? (Y/n): "
    expect_user -re "(.*)\n"
    set var1 $expect_out(1,string)

    foreach name { bob jim jacobo henric } {
        puts "hello $name $var1"
    }
'

Output:

10
Confirm? (Y/n): Y
hello bob Y
hello jim Y
hello jacobo Y
hello henric Y
Sign up to request clarification or add additional context in comments.

Comments

0

Thanks a lot, it worked as a charm. But it has some issues when the array elements are passed via parameter like this:

function a {
names=$1
expect -c '
 foreach name { $names } {
        puts "$name"
    }
'
}

It just prints:

 $names

1 Comment

You are getting into the "quoting hell" of mixing different programming languages in one file. You want to temporarily break out of the single quotes for the expect code, let the shell expand the variable and then resume the expect code in single quotes: foreach name { ' "$names" ' } {
0

you mean that any variable must be wrap around by single and double quotes?

 ' "$variable" ' 

Comments

0

ok I decided to put the expect code in a separate script test.ex:

set interfaces [lindex $argv 0]
foreach int { $var} {
puts $int
}

When I call the expect it does not cycle over the strings elements:

test.ex "string1 string2"

as it just prints:

$var

It is just ignoring the variable content, and it handles the variable as a string itself without expanding it, is there a way to get it work?

Comments

0

I figured it out! Just needed to remove the curly brackets {} around the variable that need to be looped over:

set interfaces [lindex $argv 0]
foreach int $var {
puts $int
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.