Page 1 of 1

Using pipes in the Gambas Exec command.

Posted: Monday 13th February 2017 9:34am
by casperl
For CLI utilities written in Gambas, there is a hack that allows the Unix pipe command in an Exec statement by sending keys to tmux.

Code: Select all

Exec ["tmux", "send-keys", "cat foo | grep bar" & "\r\n"] 
The above command lists the contents of the file named 'foo' to the terminal while piping the output to grep to list all locations of 'bar'. I do this exact thing hundreds of times daily, since it takes a fraction of a second to list a > 10,000 line file and to display the occurrences of the text I am searching for. I can now build a powerful set of CLI commands that automates things and eliminates tedious typing.

For this to work, the Gambas CLI executable app has to be executed from a shell (CLI) with TMUX already active.
The last two characters, "\r\n" inserts a carriage return and newline at the end of the string sent to tmux to simulate the user pressing the Enter key.

While this looks trivial, it means Gambas + tmux can be used to manipulate the terminal in just about any possible way which allows for extremely powerful scripts to be written in Gambas. This will allow actions such as changing the active directory in the shell that called the script. Such a directory change will then survive the script termination, something that is impossible by design in the Linux security model.

Re: Using pipes in the Gambas Exec command.

Posted: Monday 13th February 2017 9:57am
by casperl
Something more, if you are going to execute numerous send-keys commands to tmux from within Gambas, insert a shell command to let the system sleep for a second in between the statements. In this case I am using the shell command to wait for a second, though there are probably cases where a delay should be crafted in Gambas code using the Wait command.

Code: Select all

Exec ["tmux", "send-keys", "foo" & "\r\n"]
Exec ["sleep", "1"]
Exec ["tmux", "send-keys", "bar" & "\r\n"]

Re: Using pipes in the Gambas Exec command.

Posted: Monday 13th February 2017 7:11pm
by jornmo
This may come in handy! Thanks for sharing!

Re: Using pipes in the Gambas Exec command.

Posted: Tuesday 14th February 2017 4:20pm
by cogier
The "|" pipe can't be used outside a Terminal so wont work with Exec. 'tmux' is a Terminal which is why it works.

As you need to open a Terminal anyway why not just use the Shell command which will allow the use of the "|" pipe?

Code: Select all

Shell "ls -a | grep loc" 
or

Code: Select all

Shell "ls -a | grep loc" Wait
or

Code: Select all

Shell "ls -a | grep loc" to sVariable
Or did I miss something?