Chapter 2. How to write and execute script files?

A script in Obix is a set of any number of source code instructions. A single script can be stored in a text file and then be executed by providing the script's path on the command line.

Example:


All instructions available in Obix can be used in script files. For example, to create a simple loop displaying Hello world 3 times, replace the code in the hello.osc file you created in the previous step with the code below, then compile and execute it again.

repeat 3 times
   system.console.write_line ( "Hello world" )
end

[Note]Note

Within a script you can access input arguments which are provided on the command line. The command line arguments are available as a list of strings in input argument command_line_arguments. The following script shows how to read the values:

if i_command_line_arguments #r void then

   system.console.write_line ( "Number of command line arguments: " & i_command_line_arguments.item_count.to_string )

   repeat for each string argument in i_command_line_arguments
      system.console.write_line ( argument )
   end

else
   system.console.write_line ( "There are no command line arguments." )

end if

Save the above source code in file tests/script_arguments_test.osc and then execute it by entering the following command in your console:

on Linux:
../obix.sh script_arguments_test.osc Hello Lisa Simpson

on Windows:
..\obix script_arguments_test.osc Hello Lisa Simpson

The output displayed in your console will be:

Number of command line arguments: 4
script_arguments_test.osc
Hello
Lisa
Simpson

As you can see, the name of the script file is contained in the first argument.


[Note]Note

If you use a Unix-like system (e.g. Linux), you can turn an Obix script file into a first class executable, by using the so-called shebang syntax.

For example, insert a first line as shown below in file hello.osc (replace /usr/local/obix-0.7.4/ with Obix's root directory on your system) :

#!/usr/local/obix-0.7.4/obix.sh
repeat 3 times
   system.console.write_line ( "Hello world" )
end

Make hello.osc executable with:

chmod a+x hello.osc

Now you can execute hello.osc by simply typing

./hello.osc

Scripts can be very handy to quickly write small tests or tools you want to use on your PC, because you can use all instructions and all libraries available in Obix and Java, but without the need to create and maintain a project. For more examples please go to the projects subdirectory and look for any directory that includes execute_script in its name.

Sometimes you might want to use existing software components available in Java. In this case you can easily embed Java source code in a script. The next chapter shows how to do this.