Here is a very simplified example:
# expect -c "spawn socat -v -,raw,echo=0,nonblock /dev/ttyS0; interact"
expect executes an in-line script, which spawns socat in order to connect to a serial device. But what if we have a bash function called serial (which is quite handy):
# serial(){ socat -v -,raw,echo=0,nonblock /dev/ttyS0;}
# expect -c "spawn serial; interact"
spawn serial
couldn't execute "serial": no such file or directory
while executing
"spawn serial"
Is it possible to force expect to execute a function, without a wrapper script or binary?
You can export the shell function so a new spawned shell can call it. For example:
% cat foo.sh
the_func()
{
echo hello world
}
export -f the_func
expect -c "spawn bash -c the_func; interact"
% bash foo.sh
spawn bash -c the_func
hello world
%
To run a bash function or builtin inside spawn, you have to make the spawn be of a bash subprocess that runs the function or builtin. This is done via the -c option to bash, which lets you give a little inline script for bash to run.
spawn bash -c "serial"
Remember that the single argument after -c is the inline script to run. Arguments after that get assigned to bash's positional parameters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With