You can invoke Gforth with an image file image instead of the
default gforth.fi with the -i
flag (see Invoking Gforth):
gforth -i image
If your operating system supports starting scripts with a line of the
form #! ...
, you just have to type the image file name to start
Gforth with this image file (note that the file extension .fi
is
just a convention). I.e., to run Gforth with the image file image,
you can just type image instead of gforth -i image
.
This works because every .fi
file starts with a line of this
format:
#! /usr/local/bin/gforth-0.4.0 -i
The file and pathname for the Gforth engine specified on this line is
the specific Gforth executable that it was built against; i.e. the value
of the environment variable GFORTH
at the time that
gforthmi was executed.
You can make use of the same shell capability to make a Forth source file into an executable. For example, if you place this text in a file:
#! /usr/local/bin/gforth ." Hello, world" CR bye
and then make the file executable (chmod +x in Unix), you can run it
directly from the command line. The sequence #!
is used in two
ways; firstly, it is recognised as a “magic sequence” by the operating
system39 secondly it is treated as a comment character by
Gforth. Because of the second usage, a space is required between
#!
and the path to the executable (moreover, some Unixes
require the sequence #! /
).
Most Unix systems (including Linux) support exactly one option after the binary name. If that is not enough, you can use the following trick:
#! /bin/sh : ## ; 0 [if] exec gforth -m 10M -d 1M $0 "$@" [then] ." Hello, world" cr bye \ caution: this prevents (further) processing of "$@"
First this script is interpreted as shell script, which treats the
first two lines as (mostly) comments, then performs the third line,
which invokes gforth with this script ($0
) as parameter and its
parameters as additional parameters ("$@"
). Then this script
is interpreted as Forth script, which first defines a colon definition
##
, then ignores everything up to [then]
and finally
processes the following Forth code. You can also use
#0 [if]
in the second line, but this works only in Gforth-0.7.0 and later.
The gforthmi approach is the fastest one, the shell-based one
is slowest (needs to start an additional shell). An additional
advantage of the shell approach is that it is unnecessary to know
where the Gforth binary resides, as long as it is in the $PATH
.
#!
( – ) gforth-0.2 “hash-bang”
An alias for \
The Unix kernel actually recognises two types of files: executable files and files of data, where the data is processed by an interpreter that is specified on the “interpreter line” – the first line of the file, starting with the sequence #!. There may be a small limit (e.g., 32) on the number of characters that may be specified on the interpreter line.