Kenny McCormack <
gaz...@shell.xmission.com> wrote:
> I have a portion of an Expect script that looks something like:
>
> set someVar [exec bash -c {
> # Lots of bash script code that does stuff, then eventually
> # calculates $Result
> # ...
> # Finally, echo Result back to the calling script.
> echo $Result
> }]
>
> It works, but there is a slight problem. The problem is that
> anywhere in the bash code that I want to do normal terminal I/O, I
> have to redirect with either "< /dev/tty" or "> /dev/tty" or both.
> In particular, if I forget to redirect, say, an "echo" statement,
> then the output of that echo statement ends up in someVar - screwing
> up the Expect script, since it expects to see only the actual result
> in that variable.
>
> So, as I say, I've got it working, but there was a fair amount of
> hair-pulling involved, as I kept forgetting to do the redirection.
> My question is: Is there any cleaner way to do this?
One 'cleaner' way, if your code is as you show (meaning you have
control of the bash code) is to utilize Bash's grouping ability to
redirect the whole script output somewhere, then echo the result just
after the group terminates:
man bash:
{ list; }
list is simply executed in the current shell environment.
list must be terminated with a newline or semicolon.
This is known as a group command. The return status is
the exit status of list. Note that unlike the
metacharacters ( and ), { and } are reserved words and
must occur where a reserved word is permitted to be
recognized. Since they do not cause a word break, they
must be separated from list by whitespace or another
shell metacharacter.
So you could surround all of your bash code with {}'s, then redirect
all output from the {} group somewhere, then echo your result:
{ your normal
bash code
goes here; } >& /dev/null
echo $Result
Note, substitute whatever you like, for /dev/null.