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

SHELL

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

Executes a command by running a child process through a system shell.

An internal Process object is created to manage the command.

Standard syntax

The command is a string containing a command passed to the system shell (/bin/sh).

  • If WAIT is specified, then the interpreter waits for the command to end. Otherwise, the command is executed in the background.

    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, you can send data to the command standard input by using the Process object with common output instructions: PRINT, WRITE, ... Note that you need a reference to the Process object for that.

    • If READ is specified, events are generated each time the command sends data to its standard output streams: The Read event is raised when data is sent to the standard output stream, and the Error event is raised when data are 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, the process will be executed inside a virtual terminal. That means, the process will recognize itself 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.

Quick syntax

If you use the second syntax, the command is executed, the interpreter waiting for its end, and the complete command output is put in the specified string.

You have no control on the executed process.

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

If you need to mix both output, use the shell redirection syntax:
Shell "command 2>&1" To Result

Environment

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

[ Process = ] SHELL 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 running inside a virtual terminal, i.e. if you use the syntax FOR INPUT / OUTPUT, 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.

Specifying The Shell

Since 3.1

You can specify which shell is used for running the command by overwriting the System.Shell property.

By default, the shell command is executed via /bin/sh.

Argument quoting

Since arguments are sent to a shell, you have to quote them, as if you were typing the command in a terminal screen.

SHELL "perl -e 'print while <>;'" FOR READ WRITE

Or you can use the Shell$ function to create a quoted string that won't be modified by the shell.

Examples

' Get the contents of a directory and print it to the standard output
Shell "ls -la /tmp" Wait

' Get the contents of a directory to a string
Dim Result As String

Shell "ls -la /tmp" To Result

' Get the contents of a directory in background

Dim Result AS String

Shell "ls -la /tmp" For Read As "Process"

...

Public Sub Process_Read()

  Dim sLine AS String

  sLine = Read #Last, -256

  Result &= sLine
  Print sLine;

End

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

Unlike the VB Shell command, which returns a process ID and relies on the programmer to make API calls to control the process, the Gambas Shell function optionally returns a Process object (if used as an assignment to a variable declared AS) which can be used to directly kill or otherwise control the spawned process. Additionally, the process may be run synchronously or asynchronously, in contrast to the VB equivalent.

See also