Expect Escaping with Awk

2019-09-02 08:15发布

问题:

I need to process the output of a single record psql query through awk before assigning it to a value in my expect script.

The relevant code:

spawn $env(SHELL)
send "psql -U safeuser -h db test -c \"SELECT foo((SELECT id FROM table where ((table.col1 = \'$user\' AND table.col2 IS NULL) OR table.col2 = \'$user\') AND is_active LIMIT 1));\" | /bin/awk {{NR=3}} {{ print $1 }}; \r"
expect "assword for user safeuser:"
send "$safeuserpw\r"
expect -re '*'
set userpass $expect_out(0, string)

When I run the script, I get:

spawn /bin/bash can't read "1": no such variable "send "psql -U safeuser -h db test -c \"SELECT foo((SELECT id FROM table where ((table.col1 = \'$user\' AND table.col2..."

Is there something glaring that I'm missing here? I was under the impression that the double curly-brackets protected the awk code block.

回答1:

The awk script will show all lines because you're using '=' instead of '==' in the conditional expression. Try the following:

spawn $env(SHELL)
send "psql -U safeuser -h db test -c \"SELECT foo((SELECT id FROM table where ((table.col1 = \'$user\' AND table.col2 IS NULL) OR table.col2 = \'$user\') AND is_active LIMIT 1));\" | /bin/awk \'NR==3 { print $1 }\'; \r"
expect "assword for user safeuser:"
send "$safeuserpw\r"
expect -re '*'
set userpass $expect_out(0, string)


回答2:

Your send line is being evaluated by tcl because it is in quotes "". if you want to pass it as it should be you should change your awk portion to escape the $ :

...| /bin/awk \'NR==3 { print \$1 }\'; \r"



标签: awk expect