Gambas Documentation
Application Repository
Code Snippets
Compilation & Installation
Components
Controls pictures
Deprecated components
Developer Documentation
Development Environment Documentation
Documents
Error Messages
Gambas Playground
How To's
Language Index
#Else
#Endif
#If
+INF
-INF
Abs
Access
ACos
ACosh
Alloc
AND
AND IF
Ang
APPEND
Arithmetic Operators
Array Declaration
AS
Asc
ASin
ASinh
Asl
Asr
ASSERT
Assignment Operators
Assignments
ATan
ATan2
ATanh
Base$
Base64$
BChg
BClr
BEGINS
Bin$
Binary Data Representation
Bool@
Boolean@
BREAK
BSet
BTst
BYREF
Byte@
CASE
CATCH
CBool
Cbr
CByte
CDate
Ceil
CFloat
CHGRP
CHMOD
Choose
CHOWN
Chr$
CInt
CInteger
CLASS
CLong
CLOSE
Comp
Comparison methods
Complex numbers
CONST
Constant Declaration
Constant Expression
CONTINUE
Conv$
Conversion Functions
COPY
Cos
Cosh
CPointer
CREATE
CREATE PRIVATE
CREATE STATIC
CShort
CSingle
CStr
CString
CVariant
Datatypes
Date
Date@
DateAdd
DateDiff
Day
DConv$
DEBUG
DEC
Dec
DEFAULT
Deg
DFree
DIM
Dir
DIV
DO
DOWNTO
EACH
ELSE
END
ENDIF
ENDS
END SELECT
END STRUCT
END WITH
ENUM
Enumeration declaration
Eof
ERROR
ERROR TO
Eval
Even
EVENT
Event Loop
Events declaration
EXEC
Exist
Exp
Exp2
Exp10
Expm
EXPORT
EXTERN
External Function Declaration
External Function Management
FALSE
FAST
FAST UNSAFE
File & Directory Paths
FINALLY
Fix
Float@
Floor
FLUSH
FOR
FOR EACH
Format$
Frac
Free
FromBase
FromBase64$
FromUrl$
FUNCTION
Global Special Event Handlers
GOSUB
GOTO
Hex$
Hour
Html$
Hyp
IF
IIf
IN
INC
INCLUDE or #INCLUDE
INHERITS
Inline Arrays
Inline Collections
INPUT
INPUT FROM
InStr
Int
Int@
Integer@
IS
IsAlnum
IsAscii
IsBlank
IsBoolean
IsDate
IsDigit
IsDir
IsFloat
IsHexa
IsInf
IsInteger
IsLCase
IsLetter
IsLong
IsLower
IsMissing
IsNaN
IsNull
IsNumber
IsPunct
IsSpace
IsUCase
IsUpper
KILL
Labels
Language Constants
LAST
LCase$
Left$
Len
LET
LIBRARY
LIKE
LINE INPUT
LINK
Localization and Translation Functions
Local Variable Declaration
LOCK
Lof
Log
Log2
Log10
Logical Operators
Logp
Long@
LOOP
Lsl
Lsr
LTrim$
Mag
MATCH
Max
ME
Method Declaration
Mid$
Min
Minute
MkBool$
MkBoolean$
MkByte$
MkDate$
MKDIR
MkFloat$
MkInt$
MkInteger$
MkLong$
MkPointer$
MkShort$
MkSingle$
MOD
Month
MOVE
NEW
NEXT
NOT
Now
NULL
Oct$
Odd
ON GOSUB
ON GOTO
OPEN
OPEN MEMORY
OPEN MEMORY
OPEN NULL
OPEN PIPE
OPEN PIPE
OPEN STRING
Operator Evaluation Order
OPTIONAL
OR
OR IF
OUTPUT
OUTPUT TO
PEEK
Pi
Pointer@
PRINT
PRIVATE
PROCEDURE
PROPERTY
Property Declaration
PUBLIC
QUIT
Quote$
Rad
RAISE
Rand
RANDOMIZE
RDir
READ
Realloc
REPEAT
Replace$
RETURN
Right$
RInStr
RMDIR
Rnd
Rol
Ror
Round
RTrim$
Scan
SConv$
Second
SEEK
Seek
SELECT
Sgn
SHELL
Shell$
Shl
Short@
Shr
Sin
Single@
Sinh
SizeOf
SLEEP
Space$
Special Methods
Split
Sqr
Stat
STATIC
STEP
STOP
STOP EVENT
Str$
Str@
String$
String@
String Operators
StrPtr
STRUCT
Structure declaration
SUB
Subst$
SUPER
SWAP
Swap$
Tan
Tanh
Temp$
THEN
Time
Timer
TO
Tr$
Trim$
TRUE
TRY
TypeOf
UCase$
UnBase64$
UNLOCK
UnQuote$
UNTIL
Url$
USE
User-defined formats
Using reserved keywords as identifiers
Val
Variable Declaration
VarPtr
WAIT
WATCH
Week
WeekDay
WEND
WHILE
WITH
WRITE
XOR
Year
Language Overviews
Last Changes
Lexicon
README
Search the wiki
To Do
Topics
Tutorials
Wiki License
Wiki Manual

EXEC

[ Process = ] EXEC Command [ WAIT ] [ FOR { { READ | INPUT } | { WRITE | OUTPUT } } ] [ AS Name ]

EXEC Command TO Variable [ WITH ERROR ]

Executes a command by running a child process.

An internal Process object is created to manage the command.

Standard syntax

The Command passed to EXEC must be specified as either a list of comma delimited string constants or as an array. The first element in the list/array is the name of the command, and the other elements are the commands parameters (if any).

  • If WAIT is specified, then the interpreter waits for the command to complete, otherwise the command is run in background and your program will continue executing.

    Don't forget the WAIT keyword if you want to chain commands, otherwise the second one will start before the first one is finished!

  • If FOR is specified, then the command input-outputs are redirected so that your program intercepts them:

    • If WRITE is specified, data can be sent to the command standard input by using the Process object with common output instructions: PRINT, WRITE, ... Note that a reference to the Process object is required.

    • If READ is specified, then events will be generated each time the command sends data to its standard output stream: the Read event is raised when data is sent to the standard output stream, and the Error event is raised when data is sent to the standard error stream. Use the process object with Stream & Input/Output functions to read the process standard output.

    • If you use the INPUT and OUTPUT keywords instead of READ and WRITE, then the process is executed inside a virtual terminal. The process will think it's running inside a true terminal.

  • Name is the event name used by the Process object. By default, it is "Process".

    In Gambas 3, there is no default event name anymore.

    In other words, you must add AS "Process" to get the same behaviour as Gambas 2.

You can get a reference to the internal Process object created by using an assignment.

Program Search

The command can be specified as an absolute path or as a program name.

If the command is specified as a program name, then that program is searched through the PATH environment variable. That feature is handy, but slows down the start-up time.

Since 3.6

You can use the System.Find method to search for a program through the PATH environment variable.

Then you can store the returned absolute path in a variable, and use it later with EXEC to start the program without having to repeat the search procedure.

Quick Syntax

If you use the second form of the syntax,
EXEC Command TO Variable
the interpreter waits for the command to complete, and then places the complete command output in the specified string.

During execution of the command you have no control over the process being executed.

Only the standard output of the process is retrieved. The error output is not redirected.

Since 3.17

Since Gambas 3.17, it is possible to redirect both the standard output and the error output to the string by using the following syntax.

EXEC Command TO Variable WITH ERROR

Environment

You can specify new environment variables for the running process by using the WITH keyword just after the command argument:

[ Process = ] EXEC Command WITH Environment ...

Environment is an array of strings, each string having the following form: "NAME=VALUE". NAME is the name of the environment variable, VALUE is its value.

If you want to erase an environment variable, just use the string "NAME=".

Running Inside A Virtual Terminal

If the process is run inside a virtual terminal, i.e. if you use the FOR INPUT / OUTPUT syntax, then you can send control characters to the process standard input to get the same effect as if you enter them inside a real terminal. ^C stops the process, ^Z suspends it, and so on.

A virtual terminal has only one output. Consequently, the standard error output of the running process is received through the Read event.

Some programs have a command-line interface that is accessible only if running inside a virtual terminal.

If you plan to control an application by sending commands to standard input then testing should be performed outside of the IDE (i.e. make an executable and launch it from the command line) as the console within the development environment is not a true virtual terminal and will cause unexpected results.

The IDE console is now a true terminal emulator since Gambas 3.9.

Examples

' Get the contents of a directory
EXEC [ "ls", "-la", "/tmp" ] WAIT

' Get the contents of a directory into a string
DIM sOutput AS String
EXEC [ "ls", "-la", "/tmp" ] TO sOutput
Print sOutput

' How to give a value to an option: Print contents of /tmp directory, except gambas temporary
' directories, using the --hide option to ls.

' Either use = to separate the long option from the value and put both into one array member
Exec ["ls", "-l", "--hide=*gambas*", "/tmp"] Wait

' Or use a new array member. This must be used with short options.
Exec ["ls", "-l", "--hide", "*gambas*", "/tmp"] Wait

' Get the contents of a directory into a string, but in background
Public sOutput As String

Public Sub Main()

' A specific event name is used
Exec ["ls", "-la", "/tmp"] For Read As "Contents"

End

Public Sub Contents_Read()

  Dim sLine As String

  Read #Last, sLine, -256

  sOutput &= sLine

End

Public Sub Contents_Kill()

  Print sOutput

End

If you want to know how many bytes you can read in a Process_Read event handler, use the Lof function.

As arguments are sent directly to the process, you do not have to quote them, as you must do in a shell.

' perl -e 'print while <>;' becomes

EXEC [ "perl", "-e", "print while <>;" ] FOR READ WRITE

See also