User Tools

Site Tools


5.4.1 Gambas scripts (local)

All language elements of gambas can be used in the Gambas scripts. The structure of a Gambas script as a text file is not formalized except for the header. You can freely assign the file extension. You should follow the suggestion to use gbs3 as extension. The following script shows a proven format:

#!/usr/bin/env gbs3

  PRINT " Current date: " & SetDateToGerman(Now) & "."
  PRINT " It was precisely " & Format$(Now, "hh:nn:ss") & " Clock!"
END ' Main()

PRIVATE FUNCTION SetDateToGerman(dDatum AS Date) AS String

  DIM aMonatMatrix, aWochenTagMatrix AS NEW String[]
  DIM sWochenTag, sTag, sMonat, sJahr AS String

  aMonatMatrix = ["January", "February", "March", "April", "May", "June", "July", "August",
              "September", "October", "November", "December"]
  aWochenTagMatrix = Split("Sunday Monday Tuesday Wednesday Thursday Friday Saturday"., " ")

  sWochenTag = aWochenTagMatrix[WeekDay(dDatum)]
  sTag = Str(Day(dDatum))
  sMonat = aMonatMatrix[Month(dDatum) - 1]
  sJahr = Str(Year(dDatum))

  RETURN sWochenTag & " - " & sTag & ". " & sMonat & " " & sJahr ' Formatierter String



  • The first line is the so called Magic Header: #! /usr/bin/env gbs3
  • The procedure Main () summarizes and executes all statements as well as the declared functions and procedures.
  • You must use the Print command for all output.
  • Each print command ends with a line break. You can prevent this by terminating the print command with a semicolon.
  • Comments may be in the source code within functions or procedures.
  • If you insert a comment after the last' End' - for example at the end of the function SetDateToGerman (…) - you get an error message!

The above-mentioned content is stored in the file date_time2. gbs3 in the home directory. The file is then made executable:

hans@linux:~$ chmod u+x ./date_time2.gbs3
hans@linux:~$ ls -l # Kontrolle
-rwxr-xr-x   1 hans hans    1041 Dez 30 15:24 date_time2.gbs3

The Gambas script file date_time2. gbs3 is called in a console. The current date and the (system) time are displayed:

hans@linux:~$ gbs3 ./date_time2.gbs3
 Current date: Tuesday - 1 January 2013.
 It was exactly 15:26:25!

The function SetDateToGerman (..) could also have been replaced by this line:

PRINT " Current date: " & Format(Now, "dddd - dd. mmmm yyyy" ) & "."

Using the function SetDateToGerman (..) should only show you how to use different language elements of Gambas in the script source code. This is an advantage compared to conventional scripting languages, which you will only recognize with extensive scripts - a language for different tasks! Example 1

The following script reads and displays the environment variables:

#!/usr/bin/env gbs3

  Print "Display environment variables"
  Print "--------------------------------"
END ' Main()

Public Sub GetEnviroment()
  DIM sElement as String

  FOR EACH sElement IN Application.Env
      Print sElement & " ---> " & Application.Env[sElement]
  NEXT ' sElement


The call in the console is made with

hans@linux:~$ gbs3 ./enviroment.gbs3

and returns the environment variables as name-value pairs, each separated by the symbol' —→':

LC_PAPER ---> de_DE.UTF-8
SSH_AGENT_PID ---> 1856
GPG_AGENT_INFO ---> /tmp/keyring-XpXASO/gpg:0:1
TERM ---> xterm
SHELL ---> /bin/bash
XAUTHORITY ---> /home/hans/.Xauthority
LC_NAME ---> de_DE.UTF-8
_ ---> /usr/local/bin/gbs3 Example 2

This Gambas script outputs the currently used memory, ignoring some memory segments:

#!/usr/bin/env gbs3

Public Sub Main()
  Print "--> The currently used memory is " & CStr(GetUsedMemory()) & " Byte."
End ' Main()

Private Function GetUsedMemory() As Integer
  Dim sExecResult, sValue As String
  Dim aResult As String[]
  Dim cValue As New Collection

  Exec ["cat", "/proc/meminfo"] To sExecResult
  For Each sValue In Split(sExecResult, "\n", "", True)
      aResult = Split(sValue, " ", "", True)
      cValue[Left$(aResult[0], -1)] = aResult[1]
  Next ' sValue

  Return cValue!MemTotal - cValue!MemFree - cValue!Buffers - cValue!Cached +
         cValue!SwapTotal - cValue!SwapFree - cValue!SwapCached

The script can then be called in a terminal and outputs the used memory:

hans@linux:~$ gbs3 ./speicher.gbs3
--> The currently used memory is 649116 bytes.

It is also possible to display the more than 40 memory segments directly in a terminal - but without the manipulations in the GetUsedMemory () function, which are only possible and used in one script:

hans@linux:~$ cat /proc/meminfo
MemTotal:        8093648 kB
MemFree:         6519468 kB
Buffers:          145764 kB
DirectMap4k:       63104 kB
DirectMap2M:     8241152 kB
hans@linux:~$ Example 3

Connecting to a database and reading and displaying selected database data is also no problem for a Gambas script. Here is the source code for the tb_sqlite3. gbs3 script:

#!/usr/bin/env gbs3

USE "gb.db"
USE "gb.db.sqlite3"

Public cDBVerbindung As New Connection

Public Sub Main()
  Dim iDatensatzNummer, iSpaltenNummer As Integer
  Dim sFehler, sFeldName, sSQL_Anweisung As String
  Dim rDBResult As Result

' Syntax:   goDBServer(  TYP,     HOST,               USER,PASS, DATENBANK,    PORT,TABELLE)
  sFehler = goDBServer("sqlite3", User.Home &/ "Liste", "", "", "liste.sqlite", "", "liste")
  If sFehler = "DBError" Then
     Print " A DB connection to the DB server could not be established!"
  Endif ' sFehler = "DBError" ?

  sSQL_Anweisung = "SELECT * FROM liste"
  rDBResult = cDBVerbindung.Exec(sSQL_Anweisung)

  If rDBResult.Count = 0 Then
     Print "The number of selected records is zero!"

  Print "Report vom " & Format(Now, "dd. mmmm yyyy") & " - " & Format$(Now, "hh:nn") & " Clock"
  Print "-------------------------------------------------"

  IF rDBResult.Available THEN

  For iDatensatzNummer = 0 To rDBResult.Count - 1
   For iSpaltenNummer = 0 To rDBResult.Fields.Count - 1
    Print Upper(rDBResult.Fields[iSpaltenNummer].Name) & " ---> " & rDBResult[iSpaltenNummer]
   Next ' Spalte
  Next ' Dataset

  Endif ' MDataBase.rDBResult.Available

  Print "===== DB-Report-Ende ==========================="

End ' Main()

Private Function goDBServer(DBType As String, DBHost As String, DBUserName As String,
                 DBUserPassword As String, DBName As String, DBPort As String,
                 DBTabellenName As String) As String

  cDBVerbindung.Type = Lower(DBType)      ' The type must be written in lower case!
  cDBVerbindung.Host = DBHost
  cDBVerbindung.User = DBUserName         ' ---> Only for MySQL and PostgreSQL
  cDBVerbindung.Password = DBUserPassword ' ---> Only for MySQL and PostgreSQL
  cDBVerbindung.Name = DBName
  cDBVerbindung.Port = DBPort             ' ---> Only for MySQL and PostgreSQL

  Try cDBVerbindung.Open()
  If Error Then Return "DBFehler" ' ERROR

  • The two statements “USE” gb. db “and” USE “gb. db. sqlite3” indicate which components are to be used additionally.

With the Gambas script mentioned above, the data records are only displayed in blocks and lines:

hans@linux:~$ gbs3 ./tb_sqlite3.gbs3

Database Report from 30 December 2012 - 16:22 hrs

ID ---> 1
SURNAME ---> Eagle
Forename ---> Anne
POSTCODE ---> 39606
STREET ---> Werbener Strasse 20
TELEPHONE LANDLINE ---> 03937864322
MOBILE PHONE ---> 01712323456
DATE OF BIRTH ---> 06/22/2005
NOTES ---> "Jugend forscht" - 2013

Error messages are also displayed in the console. In the first case, the error is caught and displayed by a separate error message, while in the second case, only the internal error routine is triggered:

hans@linux:~$ gbs3 ./tb_sqlite3.gbs3
 A DB connection to the DB server could not be established!
hans@linux:~$ gbs3 ./tb_sqlite3.gbs3
MMain.Main.26: Query failed: SQL error or missing database
1: MMain.Main.26
The website uses a temporary session cookie. This technically necessary cookie is deleted when the browser is closed. You can find information on cookies in our privacy policy.
k5/k5.4/k5.4.1/start.txt · Last modified: 30.01.2022 (external edit)

Page Tools