Executing Commands from Prolog

The built-in predicate unix/1 enables you to execute system commands from within the Prolog environment. With some limitations it works also under Windows.

Under UNIX only, to access a shell (an interactive command interpreter) from within Prolog, call

     | ?- unix(shell).
     

This command puts you within a command interpreter, from which you can execute any commands you would normally type at a command prompt. To return to Prolog, either type your end-of-file character (default: ^d), or else type exit.

Alternatively, on both UNIX and Windows, you can access the shell and execute a command all at once:

     | ?- unix(shell(Command)).
     

where Command is a Prolog atom representing the command you want to execute. For example, to obtain a listing of the files in your UNIX working directory:

     | ?- unix(shell(ls)).
     

The same example under Windows would be

     | ?- unix(shell(dir)).
     

Under UNIX, unix(shell). and unix(shell(Command)). use the command interpreter defined in your SHELL environment variable. If you want sh(1) instead, use unix(system) or unix(system(Command)).

A special case is made for the common command to change your working directory. To do so, call unix(cd(Directory)), where Directory is a Prolog atom naming the directory to change to. For example, to change to a directory named /ufs/albert, you could type:

     | ?- unix(cd('/ufs/albert')).
     

Notes:

  1. The Prolog atom for the directory name /ufs/albert is surrounded by single quotes because it contains non-alphanumeric characters.
  2. Under Windows, you can use either backward \ or forward slash /.
  3. This command only affects the current directory while in Prolog; after exiting Prolog, you will be in the directory from which Prolog was invoked.

The command unix(cd)} changes to your home directory.

For further information see ref-aos and the reference page for unix/1.