Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can expect spawn a bash function?

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?

like image 249
Ulrik Avatar asked Feb 17 '26 08:02

Ulrik


2 Answers

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
%
like image 91
pynexj Avatar answered Feb 19 '26 02:02

pynexj


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.

like image 39
Donal Fellows Avatar answered Feb 19 '26 02:02

Donal Fellows



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!