# SHELL

SHELL Command [ WAIT ] [ FOR ( READ | WRITE | READ WRITE ) [ AS Variable ]

Executes a command via a system shell. An internal Process object is created to manage the command.

- If WAIT is specified, then the interpreter waits for the command ending. Otherwise, the command is executed in background.
- 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, then events will be generated each time the command sends data to its standard output streams: the event Read is raised when data are sent to the standard output stream, and the event Error is raised when data are sent to the standard error stream. Use the process object with common input instructions to read the process standard output: INPUT, READ, or LINE INPUT.
- Lastly, you can get a reference to the internal Process object into a variable Variable by specified the AS keyword.

Example

    ' Get the content of a directory

    SHELL "ls -la > /tmp/result" WAIT
    Content = File.Load("/tmp/result")

    ' Same thing, but in background

    SHELL "ls -la > /tmp/result" FOR READ

    ...

    PUBLIC SUB Process_Read()

      DIM sLine AS String

      LINE INPUT #LAST, sLine
      Content = Content & sLine

    END

Differences from VB

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 called with the AS parameter) 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.

Tip: You may have noticed that all Process events fire the same event handlers, namely Process_Read, Process_Kill, etc. You can differentiate between processes in two ways:

1. Make each Process object global to your class and go "IF LAST.Id = Process1.Id THEN..."
2. Use Object.Attach to redirect its events to a different set of handlers.

Previous: Sgn Next: Shl