How to use OCaml as a script language?
Posted on In QAHow to use OCaml as a script language like bash and python? It will be good that I can write a script in OCaml and directly invoke it.
For example, I write a script named “script.ml” and then I can invoke it directly by
$ ./script.ml
Thanks!
Three helloworld scripts:
script3.ml
#! /usr/bin/env ocaml
print_string "Hello world!n";;
script1.ml:
#! /bin/ocaml
print_string "Hello world!n";;
script2.ml
#! /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:
OCaml as a scripting language.
ocamlscript: natively-compiled OCaml scripts.
Most preferred script:
$ cat script3.ml
#! /usr/bin/env ocaml
print_string "Hello world!n";;