Gambas Documentation
Compilación e instalación
Componentes
Controls pictures
Cómo...
Descripciones del Lenguaje
Developer Documentation
Documentacion y Recetas
Documentación del Entorno de Desarrollo
Fragmentos de código
Glosario
Índice del Lenguaje
Abs
Access
ACos
ACosh
Alloc
AND
Ang
APPEND
Array
AS
Asc
Asignación
ASin
ASinh
ATan
ATan2
ATanh
BChg
BClr
BEGINS
Bin$
BREAK
BSet
BTst
BYREF
CASE
CATCH
CBool
Cbr
CByte
CDate
CFloat
Choose
Chr$
CInt
CLASS
CLong
CLOSE
Comp
CONST
Constantes del Lenguaje
CONTINUE
Conv$
COPY
Cos
Cosh
CREATE
CREATE STATIC
CShort
CSng
CStr
Date
DateAdd
DateDiff
Day
DConv$
DEBUG
DEC
Declaracion de Arreglos
Declaración de Constantes
Declaración de Eventos
Declaración de Funciones Externas
Declaración de Métodos
Declaración de Propiedades
Declaración de Variables
Declaración de Variables Locales
DEFAULT
Deg
DFree
DIM
Dir
DIV
DO
ELSE
END
ENDIF
ENDS
END SELECT
END WITH
ENUM
Enumeration declaration
Eof
ERROR
Etiquetas
EVENT
EXEC
Exp
Exp2
Exp10
Expm
EXPORT
Expresión Constante
EXTERN
FALSE
FINALLY
FLUSH
FOR
FOR EACH
Format$
Frac
Free
FUNCTION
GOTO
Hex$
Hour
Html$
Hyp
IF
IN
INC
INPUT
INPUT FROM
InStr
Int
IsAscii
IsBlank
IsBoolean
IsByte
IsDate
IsDigit
IsDir
IsFloat
IsHexa
IsInteger
IsLCase
IsLetter
IsLong
IsNull
IsNumber
IsObject
IsPunct
IsShort
IsSingle
IsSpace
IsString
IsUCase
KILL
LAST
LCase$
Left$
Len
LIBRARY
LIKE
LINE INPUT
LINK
LOCK
Lof
Log
Log2
Log10
Logp
LOOP
LTrim$
Max
ME
Métodos especiales
Mid$
Min
Minute
MKDIR
MOD
Month
MOVE
New
NEXT
NOT
Now
NULL
OPEN
Operadores Aritméticos
Operadores de Asignación
Operadores de Cadena
Operadores Lógicos
OPTIONAL
OR
OUTPUT
OUTPUT TO
Pi
PRINT
PRIVATE
PROCEDURE
PROPERTY
PUBLIC
QUIT
Quote$
Rad
RAISE
Randomize
READ[../../def/stream] _\Stream_
Realloc
REPEAT
Replace$
RETURN
Right$
RInStr
RMDIR
Rnd
Rol
Ror
Round
RTrim$
SConv$
Second
Seek
SELECT
Sgn
Shell$
Shl
Shr
Sin
Sinh
SLEEP
Space$
Split
Sqr
Stat
STATIC
STEP
STOP
STOP EVENT
Str$
String$
StrPtr
SUB
Subst$
SUPER
SWAP
Tan
Tanh
Temp$
THEN
Time
Timer
Tipos de Datos
TO
Trim$
TRUE
TRY
TypeOf
UCase$
UNLOCK
UNTIL
Val
WAIT
WATCH
Week
WeekDay
WEND
WHILE
WITH
WRITE
XOR
Year
LÉEME
Licencia del Wiki
Manual del Wiki
Mensajes de Error
Pendiente de traducción
Registrarse
Repositorio de Aplicaciones
Tutoriales
Últimos cambios

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

Desde 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