6.23 OS command line arguments

The usual way to pass arguments to Gforth programs on the command line is via the -e option, e.g.

gforth -e "123 456" foo.fs -e bye

However, you may want to interpret the command-line arguments directly. In that case, you can access the (image-specific) command-line arguments through next-arg:

next-arg ( – addr u  ) gforth-0.7 “next-arg”

get the next argument from the OS command line, consuming it; if there is no argument left, return 0 0.

Here’s an example program echo.fs for next-arg:

: echo ( -- )
    begin
	next-arg 2dup 0 0 d<> while
	    type space
    repeat
    2drop ;

echo cr bye

This can be invoked with

gforth echo.fs hello world

and it will print

hello world

The next lower level of dealing with the OS command line are the following words:

arg ( u – addr count  ) gforth-0.2 “arg”

Return the string for the uth command-line argument; returns 0 0 if the access is beyond the last argument. 0 arg is the program name with which you started Gforth. The next unprocessed argument is always 1 arg, the one after that is 2 arg etc. All arguments already processed by the system are deleted. After you have processed an argument, you can delete it with shift-args.

shift-args ( ) gforth-0.7 “shift-args”

1 arg is deleted, shifting all following OS command line parameters to the left by 1, and reducing argc @. This word can change argv @.

Finally, at the lowest level Gforth provides the following words:

argc ( – addr  ) gforth-0.2 “argc”

Variable – the number of command-line arguments (including the command name). Changed by next-arg and shift-args.

argv ( – addr  ) gforth-0.2 “argv”

Variable – a pointer to a vector of pointers to the command-line arguments (including the command-name). Each argument is represented as a C-style zero-terminated string. Changed by next-arg and shift-args.