Execute bash script within OCaml [SOLVED]

Is it possible to execute bash scripts within Ocaml code ?

I thought of using Sys.command “bash my_script” but on my example this returns a 255 error (means an “out-of-range” error, not sure how to interpret it) and does not work.

This should be the way to do it.

E.g. here Sys.command "bash" in ocaml will take me to a shell prompt and back when I’m finished.

Does my_script maybe call exit with a value out of 0-255 ?

Note that the script seemingly executes without any problems if I launch it outside OCaml. It is rather short, and simply reads a PHP¨ file and writes the output on a file.

Here goes the script’s content :

#! /bin/bash

/Applications/MAMP/bin/php/php5.6.7/bin/php-cgi -f
/Users/jonathandoyle/Documents/Sites/Rachel/public_html/iewtopic.php
f=42 p=5554 > /Users/jonathandoyle/Documents/Sites/Rachel/public_html/temp.txt;

Just to make sure what is the result of:

bash my_script
echo $?

The result is 0 when the PHP executes without errors and 255
when it contains errors.

I’ve just checked that OCaml does the correct thing when there is no error in the PHP script, but Iwant to be able to do things even when there are errors in the PHP.
The problem with OCaml is that in the error case, it will not
print the error message on the temp.txt log file as the bash script
outside OCaml would.

To be clear, what I said in my last post wasn’t clear at all to me at the beginning, and there is now an easy fix : test if Sys.command is zero to know if there is an error or not.

But I’m still curious to know why OCaml acts slightly differently from bash in this case.

Is it also the case if you invoke the script via bash my_script rather than ./my_script ? Also maybe try bash -i but I doubt this will change anything. Are you sure the errors get written on stdout and not stderr ?

In any case I don’t think you’ll find something fishy in OCaml here, Sys.command is just a wrapper around system(3).

You’re right, bash my_script acts differently from ./myscript in this situation. Case closed, OCaml proved innocent !
Thanks for all your help.

By the way, just a general pair of notes:

  1. if your shell script lists its command interpreter explicitly in its first line via the #! mechanism and is set executable you need not specify the shell that is used to execute it. The kernel does all that nice work for you. Just pretend it’s like any other executable file.
  2. When you specify things to execute (say bash or your script), it is good style to give full path.
1 Like