0

I want to execute a script remotely with expect and a for loop:


#!/usr/bin/expect
set timeout 10

spawn ssh [email protected]
expect "password: "
send "pass\n"
expect "$ "
send "for i in `ls` ;\n"
send "do\n"
send "   STRLENGTH=$(echo -n $i | wc -m);\n"
send "   if [ $STRLENGTH -ge 35 ];\n"
send "   then echo ok \"$i\";\n"
send "   fi\n"
send "done\n"


But it gives me this error:

can't read "i": no such variable
    while executing
"send "   STRLENGTH=$(echo -n $i | wc -m);\n""
    (file "./script.sh" line 10)

Any help is appreciated, thanks!

2 Answers 2

1

expect is telling you that it tried to substitute $i for a value, but didn't find the variable i. This is not your intention: you wanted to send it literally for the remote shell to make the substitution. Escape the $ character with a backslash to make expect pass it literally.

Consider using sshpass instead of expect too.

0
1

gronostaj is the right answer. Note, you can simplify sending a series of lines into one multi-line string literal. See the wiki.

send { for i in `ls`
 do
    STRLENGTH=$(echo -n $i | wc -m)
    if [ $STRLENGTH -ge 35 ]
    then echo ok "$i"
    fi
 done
}

Using {} to enclose a string instead of "" preserves newlines and $ and so on. However, you still need to escape \, {, and } with \.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .