Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run shell command and return output as result of custom function

I would like to write a custom OpenOffice function that runs a shell command and puts the result into the cell from which it was invoked. I have a basic macro working, but I can't find a way to capture the command's output.

Function MyTest( c1 )
    MyTest = Shell("bash -c "" echo hello "" ")
End Function

The above always returns 0. Looking at the documentation of the Shell command, I don't think it actually returns STDOUT.

How would I capture the output so that I can return it in my function?

like image 495
Mark Avatar asked Jan 22 '26 00:01

Mark


2 Answers

Can you redirect the output to a temporary file, then read in the contents of that file with another command?

eg, Shell("bash -c "" echo hello > tmp.txt "" ")

like image 153
Kimball Robinson Avatar answered Jan 23 '26 17:01

Kimball Robinson


Kimbal Robinson's answer works, but has the disadvantage of using a file. It is slow (compared to using memory only), and you have to delete the file afterwards (although by putting it in /tmp, it will usually be deleted automatically eventually).

An alternative is to have the data transit via the clipboard:

Dim myCommand As String
myCommand = "echo hello world"
Shell ("bash", 1, "-c "" " & myCommand & " | xclip -selection clipboard"" ", true)
' setting the 4th parameter to true ensures that the Shell function will wait until '
' the command terminates before returning '

' then paste the content of the clipboard '
Dim dh As Object
dh = createUnoService("com.sun.star.frame.DispatchHelper")
dh.executeDispatch(StarDesktop.CurrentFrame, ".uno:Paste", "", 0, Array())

This will paste the output of the command at the current point of the active document.

Note that, if the command issues several lines, the "text import" dialog will pop up (I don't know how to prevent that).

like image 22
Pierre-Antoine Avatar answered Jan 23 '26 16:01

Pierre-Antoine