Question

I'm trying to write an expect script, which is based on Tcl. (actually I'm trying to generate expect scripts in python, and no, I can't use pyexpect)

How can I send a string without special characters (like [) being interpreted as commands?

In bash shell, I can use single quotes to write raw strings.

$ echo 'hello $world'
hello $world

But with expect, I have many problems with special characters. For example, brackets are interpreted as commands.

expect1.1> send_user "[hello]"
invalid command name "hello"
    while executing
"hello"

How can I just print the string "[hello]"?

EDIT: just enclosing a string in curly braces doesn't always work.

For example

expect1.4> send_user {h}ello}

doesn't print the string "h}ello". It gives an error:

extra characters after close-brace
    while executing
"send {h}ello}

And there is no way to escape the curly braces according to the doc.

Or what if I want to send a string starting with *} ? Rule 5 in http://tcl.tk/man/tcl8.5/TclCmd/Tcl.htm#M10 will interfere and no way to escape the * or the }.

Était-ce utile?

La solution

Curly braces inhibit all expansion*:

echo {hello $world}

You could also just escape the brackets:

Echo "hello \$world"
  • Curly braces inhibit all expansion when the statement is parsed. However, some commands may choose to do their own expansion internally. The if statement is one such command -- even with curly braces variables will get expanded. Not many commands have this behavior, though.

This is all documented in the Tcl man page. Here's a link to the section on curly braces: http://tcl.tk/man/tcl8.5/TclCmd/Tcl.htm#M10

You might also be interested in this question on stackoverflow: General string quoting for Tcl

Note that curly braces aren't magic -- you still have to apply the quoting rules. For example, you can't have unbalanced curly braces, etc. the precise quoting mechanism you need will vary depending on the data. For some strings that means curly braces, for some it means quotes, for others you might need the backslash. For still others you may need a combination along with string concatenation.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top