I am trying to loop a list of sites through an expect script. The loop will take my list and read it line by line, change directories to the folder of the site name, then pass the site name to an expect script.

Bash Script:


while read site; do
  cd /home/user/$site
  echo $site
done < $sites

Expect Script:


set site [lindex $argv 0]
set timeout 3

logfile services
spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no -oUserKnownHostsFile=/dev/null user@$site
expect "password" { send mypassword\r }
expect "#"
send environment\ no\ more\n
expect "#"
send show\ service\ service-using\n
expect "#"
send logout\n


user@myserver:~$ sh show-database.sh
show-database.sh: 11: show-database.sh: ./base.sh: not found
show-database.sh: 11: show-database.sh: ./base.sh: not found

I'm hoping to see a file called services in each folder of each site. I can run the following and it works from CLI, however it doesn't switch directories. This is just the beginning the of a much larger script, which will have a few more things to do in the loop. For now, this is what I have for testing.

./base.sh site-01


  • You have just cd-ed to a "site" directory, and you want the "./base.sh" script to exist there. Does it? – glenn jackman Oct 5 '15 at 20:34
  • Assuming "base.sh" is the expect script: 1) you don't pass the $site argument to it, and 2) *.sh" is the wrong extension for an expect script – glenn jackman Oct 5 '15 at 20:36
  • I've tested this many ways but must have missed the passing of the $site. This is now working by replacing the ./base.sh with the following line, expect /home/user/./base.sh $site – Pi4All Oct 5 '15 at 21:16
  • Also corrected the logfile with log_file. Thanks @glennjackman – Pi4All Oct 5 '15 at 21:19
  • rename base.sh to base.exp. – glenn jackman Oct 5 '15 at 21:20

You don't need the bash wrapper script for this at all, expect can handle all that:

set timeout 3

set rootdir /home/user
set sites [file join $rootdir sites.cfg]
set fh [open $sites r]

while {[gets $fh site] != -1} {
    set dir [file join $rootdir $site]
    if { ! [file isdirectory $dir]} {
        puts "*** error: $dir does not exist"

    cd $dir
    puts [pwd]
    puts $site

    log_file services

    spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no -oUserKnownHostsFile=/dev/null user@$site
    expect "password" 
    send "mypassword\r 
    expect "#"
    send "environment no more\r"
    expect "#"
    send "show service service-using\r"
    expect "#"
    send "logout\r"
    expect eof

| improve this answer | |

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.