How to use OCaml as a script language?

How 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 “” 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

I prefer The is straightforward, but it is bounded to /bin/ocaml for the ocaml command. The 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.

Answered by anonymous.

Most preferred script:

$ cat 
#! /usr/bin/env ocaml

print_string "Hello world!n";;

Leave a Reply

Your email address will not be published. Required fields are marked *