开发者

How do I embed an expect script that takes in arguments into a bash shell script?

开发者 https://www.devze.com 2023-02-02 07:08 出处:网络
I开发者_开发百科 am writing a bash script which amongst many other things uses expect to automatically run a binary and install it by answering installer prompts.

I开发者_开发百科 am writing a bash script which amongst many other things uses expect to automatically run a binary and install it by answering installer prompts.

I was able to get my expect script to work fine when the expect script is called in my bash script with the command "expect $expectscriptname $Parameter". However, I want to embed the expect script into the shell script instead of having to maintain two separate script files for the job. I searched around and found that the procedure to embed expect into bash script was to declare a variable like VAR below and then echo it.:

VAR=$(expect -c "
#content of expect script here
")
echo "$VAR"

1) I don't understand how echoing $VAR actually runs the expect script. Could anyone explain?

2) I am not sure how to pass $Parameter into VAR or to the echo statement. This is my main concern.

Any ideas? Thanks.


Try something like:

#!/bin/sh

tclsh <<EOF
puts $1
EOF

I don't have the expect command installed today, so I used tclsh instead.


In bash, the construct $(cmd) runs the specified command and captures its output. It's similar to the backtick notation, though there are some slight differences. Thus, the assignment to VAR is what runs the expect command:

# expect is run here
VAR=$(expect -c "
# ...
")

# This echoes the output of the expect command.
echo "$VAR"

From the bash manual page:

When the old-style backquote form of substitution is used, backslash retains its literal meaning except when followed by $, , or \. The first backquote not preceded by a backslash terminates the command substitution. When using the $(command)` form, all characters between the parentheses make up the command; none are treated specially.

That's why it works: The bash comment character (#) isn't treated as a comment character within the $( ... ).

EDIT

Passing parameters: Just put 'em in there. For instance, consider this script:

foo="Hello, there"
bar=$(echo "
# $foo
")
echo $bar

If you run that script, it prints:

# Hello, there

Thus, the value of $foo was substituted inside the quotes. The same should work for the expect script.


Instead of a bash script and an expect script, have you considered writing just a single expect script?

Expect is a superset of Tcl, which means it is a fully functioning programming language, and you can do anything with it that you can do with bash (and for the things that you can't, you can always exec bash commands. You don't have to use expect just to "expect" things

0

精彩评论

暂无评论...
验证码 换一张
取 消