Scripting cookbook
Factor handbook > Factor cookbook

Prev:Application cookbook
Next:Factor philosophy

Factor can be used for command-line scripting on Unix-like systems.

To run a script, simply pass it as an argument to the Factor executable:
./factor cleanup.factor

The script may access command line arguments by inspecting the value of the command-line variable. It can also get its own path from the script variable.

Example: ls
Here is an example implementing a simplified version of the Unix ls command in Factor:
USING: command-line namespaces io io.files io.pathnames tools.files sequences kernel ; command-line get [ ".". directory. ] [ dup length 1 = [ first directory. ] [ [ [ nl write ":" print ] [ directory. ] bi ] each ] if ] if-empty

You can put it in a file named ls.factor, and then run it, to list the /usr/bin directory for example:
./factor ls.factor /usr/bin

Example: grep
The following is a more complicated example, implementing something like the Unix grep command:
USING: kernel fry io io.files io.encodings.ascii sequences regexp command-line namespaces ; IN: grep : grep-lines ( pattern -- ) '[ dup _ matches? [ print ] [ drop ] if ] each-line ; : grep-file ( pattern filename -- ) ascii [ grep-lines ] with-file-reader ; : grep-usage ( -- ) "Usage: factor grep.factor <pattern> [<file>...]" print ; command-line get [ grep-usage ] [ unclip <regexp> swap [ grep-lines ] [ [ grep-file ] with each ] if-empty ] if-empty

You can run it like so,
./factor grep.factor '.*hello.*' myfile.txt

You'll notice this script takes a while to start. This is because it is loading and compiling the regexp vocabulary every time. To speed up startup, load the vocabulary into your image, and save the image:
USE: regexp save

Now, the grep.factor script will start up much faster. See Images for details.

Executable scripts
It is also possible to make executable scripts. A Factor file can begin with a 'shebang' like the following:
#!/usr/bin/env factor

If the text file is made executable, then it can be run, assuming the factor binary is in your $PATH.

Command line arguments
Application cookbook