For example, I write a script named “script.ml” and then I can invoke it directly by
Three helloworld scripts:
#! /usr/bin/env ocaml print_string "Hello world!n";;
#! /bin/ocaml print_string "Hello world!n";;
#! /bin/sh # (* exec ocaml "$0" "$@" *) use "topfind";; print_string "Hello world!n";;
Idea from findlib quickstart.
Remember to make the executable by
chmod 755 script.ml
I prefer script3.ml. The script1.ml is straightforward, but it is bounded to
/bin/ocaml for the ocaml command. The script2.ml is more complex, but use your environmental configuration for the location of the ocaml command.
Also be aware that the overall source code is compiled in total first and then is executed. Hence, no execution happens if there is some error, such as failures to compile the script. This is different from a bash script that will be executed by the interpreter until there is an error happens.
There are other discussions and tools on using OCaml as a scripting language:
Most preferred script:
$ cat script3.ml #! /usr/bin/env ocaml print_string "Hello world!n";;