Actually, these two lines should work the same.
Code:
var1="rm \$0"
var1='rm $0'
A backslash inside double quotes will escapes "$", so it wouldn't be seen as a variable. I'd still prefer the second one for readability purposes, however.
Now I'm not familiar with expect either, but in any case when you have a long string of commands to pass to an external program, it usually pays to store them in a separate variable first. It also helps readability to separate each command out in a separate line.
Code:
var1='rm $0'
commands='
spawn ssh user@192.168.1.200 ;
expect "password" ;
send "123456\n" ;
expect "@" ;
send "sudo -k\n" ;
expect "@" ;
send "sudo su\n" ;
expect "password" ;
send "123456\n" ;
expect "@" ;
send "echo '$var1'>>/home/user/config-script\n" ;
expect "@";
send "exit\n";
send "logout\n";
interact
'
expect -c "$commands"
Now we can see things more clearly. The line in question is this:
Code:
'...
send "echo '$var1'>>/home/user/config-script\n" ;
...'
Which after shell parsing is received by
expect as this:
Code:
...
send "echo rm $0>>/home/user/config-script\n" ;
...
So you are correct. It leaves $0 unprotected and subject to interpretation by
expect.
It took me a bit of trying to get it right, but all you really need to do is ensure that expect gets the values properly backslashed:
Code:
var1='rm \$0'
commands='
spawn ssh user@192.168.1.200 ;
expect "password" ;
send "123456\n" ;
expect "@" ;
send "sudo -k\n" ;
expect "@" ;
send "sudo su\n" ;
expect "password" ;
send "123456\n" ;
expect "@" ;
send "echo \"'"$var1"'\" >>/home/user/config-script\n" ;
expect "@";
send "exit\n";
send "logout\n";
interact
'
expect -c "$commands"
It seems to work in my tests, at least. YMMV.
BTW, do you really need the extra
$var1 step in the first place? Can you not just hard-code it in with the rest of the commands?
Code:
send "echo \"rm \$0\" >>/home/user/config-script\n" ;