How to run SWI-Prolog from the command line?

The other answer is more or less correct, however, how it works might depend on your OS. The most portable way to do it is, appartently:

$ cat example.pl
#!/path/to/your/swipl

:- set_prolog_flag(verbose, silent).

:- initialization main.

main :-
    format('Example script~n'),
    current_prolog_flag(argv, Argv),
    format('Called with ~q~n', [Argv]),
    halt.
main :-
    halt(1).

The difference here is that there is nothing on the shebang line apart from the path to swipl. Everything else is done using directives. On my OS, only that worked!

$ chmod u+x example.pl
$ example.pl foo bar baz
Example script
Called with [foo,bar,baz]

EDIT

It is probably cleaner to remove the shebang line altogether, and instead run from the command line:

$ swipl -s example.pl -- foo bar baz
Example script
Called with [foo,bar,baz]

Again, using a directive to set main/0 as the initialization goal saves you from having to explicitly do this on the command line. Calling swipl from the command line, on the other hand, lets your OS find where the executable is, instead of hard-coding this information in the script.


ISO directive: initialization. This should work.

:- initialization main.

main :-
  write('Hello World\n').

edit sorry, I skipped over most interesting details. Here is a sample script, let's say saved in ~/test/main.pl

#!/home/carlo/bin/swipl -f -q

:- initialization main.

main :-
  current_prolog_flag(argv, Argv),
  format('Hello World, argv:~w\n', [Argv]),
  halt(0).

and made executable with

chmod +x ~/test/main.pl

then I get

~$ ~/test/main.pl
Hello World, argv:[]

~$ ~/test/main.pl as,dnj asdl
Hello World, argv:[as,dnj,asdl]

In script main.pl, I used the swipl path that results from building from source without admin privileges. The SWI-Prolog build process put bin and lib under ~/bin and ~/lib

Note: the -f flag disables loading the initialization ~/.plrc, and this could be necessary to get more 'strict control' over execution...

I'm currently unsure if the documentation page is up-to-date with current SW status. From some mailing list message, and my own efforts to reuse thea, seems that command line flags changed recently...