Execute a system command
From Rosetta Code
You are encouraged to solve this task according to the task description, using any language you may know.
In this task, the goal is to run either the ls (dir on Windows) system command, or the pause system command.
[edit] Ada
with Interfaces.C; use Interfaces.C;
procedure Execute_System is
function Sys (Arg : Char_Array) return Integer;
pragma Import(C, Sys, "system");
Ret_Val : Integer;
begin
Ret_Val := Sys(To_C("ls"));
end Execute_System;
[edit] Aikido
The simplest way to do this is using the system() function. It returns a vector of strings (the output from the command).
var lines = system ("ls")
foreach line lines {
println (line)
}
If you don't want to process the output you can use the exec function. It writes the output to the standard output stream by default;
exec ("ls")
You also have the regular fork and execv calls available:
var pid = fork()
if (pid == 0) {
var args = ["/bin/ls"]
execv ("/bin/ls", args)
exit(1)
}
var status = 0
waitpid (pid, status)
[edit] ALGOL 68
Works with: ALGOL 68G version Any - tested with release mk15-0.8b.fc9 - "system" is not part of the standard's prelude.
system("ls")
Or the classic "!" shell escape can be implemented as an "!" operator:
Works with: ALGOL 68G version Any - tested with release mk15-0.8b.fc9 - "system" & "ANDF" are not part of the standard's prelude.
OP ! = (STRING cmd)BOOL: system(cmd) = 0;
IF ! "touch test.tmp" ANDF ( ! "ls test.tmp" ANDF ! "rm test.tmp" ) THEN
print (("test.tmp now gone!", new line))
FI
[edit] AppleScript
do shell script "ls" without altering line endings
[edit] AutoHotkey
Run, %comspec% /k dir & pause
[edit] AWK
BEGIN {
system("ls")
}
[edit] BASIC
SHELL "dir"
[edit] C
ISO C & POSIX:
#include <stdlib.h>
int main()
{
system("ls");
return 0;
}
[edit] C++
Works with: Visual C++ version 2005
system("pause");
[edit] C#
Using Windows / .NET:
using System.Diagnostics;
namespace Execute
{
class Program
{
static void Main(string[] args)
{
Process.Start("cmd.exe", "/c dir");
}
}
}
Works with: MCS version 1.2.3.1
using System;
class Execute {
static void Main() {
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.EnableRaisingEvents=false;
proc.StartInfo.FileName="ls";
proc.Start();
}
}
[edit] Clojure
(.. Runtime getRuntime (exec "cmd /C dir"))
[edit] Common Lisp
Works with: LispWorks
(system:call-system "ls")
Library: trivial-shell
(trivial-shell:shell-command "ls")
[edit] D
Note that this does not return the output of the command, other than the return value. That functionality can be accomplished via a call to shell().
std.process.system("ls");
[edit] dc
! ls
[edit] DCL
DirectoryOr, shorter
dir
[edit] E
def ls := makeCommand("ls")
ls("-l")
def [results, _, _] := ls.exec(["-l"])
when (results) -> {
def [exitCode, out, err] := results
print(out)
} catch problem {
print(`failed to execute ls: $problem`)
}
[edit] Erlang
os:cmd("ls").
[edit] Factor
"ls" run-process wait-for-process
[edit] Forth
Works with: gforth version 0.6.2
s" ls" system
[edit] Fortran
Works with: gfortran The SYSTEM subroutine (and function) are a GNU extension.
program SystemTest
call system("ls")
end program SystemTest
[edit] Go
package main
import "fmt"
import "exec"
func main() {
cmd, err := exec.Run("/bin/ls", []string{"/bin/ls"}, []string{}, "", exec.DevNull, exec.PassThrough, exec.PassThrough)
if (err != nil) {
fmt.Println(err)
return
}
cmd.Close()
}
[edit] gnuplot
!ls
[edit] Haskell
Works with: GHCi version 6.6
import System.Cmd
main = system "ls"
See also: the System.Process module
[edit] HicEst
SYSTEM(CoMmand='pause')
SYSTEM(CoMmand='dir & pause')
[edit] IDL
$ls
Will execute "ls" with output to the screen.
spawn,"ls",result
will execute it and store the result in the string array "result".
spawn,"ls",unit=unit
will execute it asynchronously and direct any output from it into the LUN "unit" from whence it can be read at any (later) time.
[edit] Io
SystemCall with("ls") run
[edit] J
The system command interface in J is provided by the standard "task" script:
load'task'
NB. Execute a command and wait for it to complete
shell 'dir'
NB. Execute a command but don't wait for it to complete
fork 'notepad'
NB. Execute a command and capture its stdout
stdout =: shell 'dir'
NB. Execute a command, provide it with stdin,
NB. and capture its stdout
stdin =: 'blahblahblah'
stdout =: stdin spawn 'grep blah'
[edit] Java
Works with: Java version 1.5+
import java.util.Scanner;
import java.io.*;
public class Program {
public static void main(String[] args) {
try {
Process p = Runtime.getRuntime().exec("cmd /C dir");//Windows command, use "ls -oa" for UNIX
Scanner sc = new Scanner(p.getInputStream());
while (sc.hasNext()) System.out.println(sc.nextLine());
}
catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
Works with: Java version 1.4+ There are two ways to run system commands. The simple way, which will hang the JVM (I would be interested in some kind of reason). -- this happens because the the inputStream buffer fills up and blocks until it gets read. Moving your .waitFor after reading the InputStream would fix your issue (as long as your error stream doesn't fill up)
import java.io.IOException;
import java.io.InputStream;
public class MainEntry {
public static void main(String[] args) {
executeCmd("ls -oa");
}
private static void executeCmd(String string) {
InputStream pipedOut = null;
try {
Process aProcess = Runtime.getRuntime().exec(string);
aProcess.waitFor();
pipedOut = aProcess.getInputStream();
byte buffer[] = new byte[2048];
int read = pipedOut.read(buffer);
// Replace following code with your intends processing tools
while(read >= 0) {
System.out.write(buffer, 0, read);
read = pipedOut.read(buffer);
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException ie) {
ie.printStackTrace();
} finally {
if(pipedOut != null) {
try {
pipedOut.close();
} catch (IOException e) {
}
}
}
}
}
And the right way, which uses threading to read the InputStream given by the process.
import java.io.IOException;
import java.io.InputStream;
public class MainEntry {
public static void main(String[] args) {
// the command to execute
executeCmd("ls -oa");
}
private static void executeCmd(String string) {
InputStream pipedOut = null;
try {
Process aProcess = Runtime.getRuntime().exec(string);
// These two thread shall stop by themself when the process end
Thread pipeThread = new Thread(new StreamGobber(aProcess.getInputStream()));
Thread errorThread = new Thread(new StreamGobber(aProcess.getErrorStream()));
pipeThread.start();
errorThread.start();
aProcess.waitFor();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
//Replace the following thread with your intends reader
class StreamGobber implements Runnable {
private InputStream Pipe;
public StreamGobber(InputStream pipe) {
if(pipe == null) {
throw new NullPointerException("bad pipe");
}
Pipe = pipe;
}
public void run() {
try {
byte buffer[] = new byte[2048];
int read = Pipe.read(buffer);
while(read >= 0) {
System.out.write(buffer, 0, read);
read = Pipe.read(buffer);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(Pipe != null) {
try {
Pipe.close();
} catch (IOException e) {
}
}
}
}
}
[edit] JavaScript
JavaScript does not have any facilities to interact with the OS. However, host environments can provide this ability.
Works with: JScript
var shell = new ActiveXObject("WScript.Shell");
shell.run("cmd /c dir & pause");
Works with: Rhino
runCommand("cmd", "/c", "dir", "d:\\");
print("===");
var options = {
// can specify arguments here in the options object
args: ["/c", "dir", "d:\\"],
// capture stdout to the options.output property
output: ''
};
runCommand("cmd", options);
print(options.output);
[edit] Joy
"ls" system.
[edit] Logo
Works with: UCB Logo The lines of output of the SHELL command are returned as a list.
print first butfirst shell [ls -a] ; ..
[edit] Lua
-- just executing the command
os.execute("ls")
-- to execute and capture the output, use io.popen
local f = io.popen("ls") -- store the output in a "file"
print( f:read("*a") ) -- print out the "file"'s content
[edit] M4
syscmd(ifdef(`__windows__',`dir',`ls'))
[edit] MAXScript
dosCommand "pause"
[edit] Make
make can use system command in either definition of variables or in the targets
in definition
contents=$(shell cat foo)
curdir=`pwd`
in target
mytarget:
cat foo | grep mytext
[edit] MATLAB
To execute system commands in MATLAB, use the "system" keyword.
Sample Usage:
>> system('PAUSE')
Press any key to continue . . .
ans =
0
[edit] Modula-3
This code requires the UNSAFE keyword because M3toC deals with C strings (which are pointers), and are implemented in Modula-3 as UNTRACED, meaning they are not garbage collected, which is why the code calls FreeCopiedS().
Also note the EVAL keyword, which ignores the return value of a function.
UNSAFE MODULE Exec EXPORTS Main;
IMPORT Unix, M3toC;
VAR command := M3toC.CopyTtoS("ls");
BEGIN
EVAL Unix.system(command);
M3toC.FreeCopiedS(command);
END Exec.
[edit] MUMPS
ANSI MUMPS doesn't allow access to the operating system except possibly through the View command and $View function, both of which are implementation specific. Intersystems' Caché does allow you to create processes with the $ZF function, and if the permissions for the Caché process allow it you can perform operating system commands.
In Caché on OpenVMS in an FILES-11 filesystem ODS-5 mode this could work:
Set X=$ZF(-1,"DIR")
[edit] Objective-C
Works with: GCC
NSTask runs an external process with explicit path and arguments.
void runls()
{
[[NSTask launchedTaskWithLaunchPath:@"/bin/ls"
arguments:[NSArray array]] waitUntilExit];
}
If you need to run a system command, invoke the shell:
void runSystemCommand(NSString *cmd)
{
[[NSTask launchedTaskWithLaunchPath:@"/bin/sh"
arguments:[NSArray arrayWithObjects:@"-c", cmd, nil]]
waitUntilExit];
}
Complete usage example:
Works with: Cocoa
Works with: GNUstep
#import <Foundation/Foundation.h>
void runSystemCommand(NSString *cmd)
{
[[NSTask launchedTaskWithLaunchPath:@"/bin/sh"
arguments:[NSArray arrayWithObjects:@"-c", cmd, nil]]
waitUntilExit];
}
int main(int argc, const char **argv)
{
NSAutoreleasePool *pool;
pool = [NSAutoreleasePool new];
runSystemCommand(@"ls");
[pool release];
return 0;
}
Or use the C method above.
[edit] OCaml
Just run the command:
Sys.command "ls"
To capture the output of the command:
#load "unix.cma"
let syscall cmd =
let ic, oc = Unix.open_process cmd in
let buf = Buffer.create 16 in
(try
while true do
Buffer.add_channel buf ic 1
done
with End_of_file -> ());
let _ = Unix.close_process (ic, oc) in
(Buffer.contents buf)
let listing = syscall "ls" ;;
a more complete version which also returns the contents from stderr, and checks the exit-status, and where the environment can be specified:
let check_exit_status = function
| Unix.WEXITED 0 -> ()
| Unix.WEXITED r -> Printf.eprintf "warning: the process terminated with exit code (%d)\n%!" r
| Unix.WSIGNALED n -> Printf.eprintf "warning: the process was killed by a signal (number: %d)\n%!" n
| Unix.WSTOPPED n -> Printf.eprintf "warning: the process was stopped by a signal (number: %d)\n%!" n
;;
let syscall ?(env=[| |]) cmd =
let ic, oc, ec = Unix.open_process_full cmd env in
let buf1 = Buffer.create 96
and buf2 = Buffer.create 48 in
(try
while true do Buffer.add_channel buf1 ic 1 done
with End_of_file -> ());
(try
while true do Buffer.add_channel buf2 ec 1 done
with End_of_file -> ());
let exit_status = Unix.close_process_full (ic, oc, ec) in
check_exit_status exit_status;
(Buffer.contents buf1,
Buffer.contents buf2)
val syscall : ?env:string array -> string -> string * string
[edit] Octave
system("ls");
[edit] Oz
{OS.system "ls" _}
A more sophisticated example can be found here.
[edit] Perl
my @results = qx(ls);
# runs command and returns its STDOUT as a string
my @results = `ls`;
# ditto, alternative syntax
system "ls";
# runs command and returns its exit status; its STDOUT gets output to our STDOUT
print `ls`;
#The same, but with back quotes
exec "ls";
# replace current process with another
Also see: http://perldoc.perl.org/perlipc.html#Using-open()-for-IPC http://perldoc.perl.org/IPC/Open3.html
[edit] PHP
The first line execute the command and the second line display the output:
@exec($command,$output);
echo nl2br($output);
Note:The '@' is here to prevent error messages to be displayed, 'nl2br' translate '\n' chars to 'br' in HTML.
Other:
$results = `ls`;
# runs command and returns its STDOUT as a string
system("ls");
# runs command and returns its exit status; its STDOUT gets output to our STDOUT
echo `ls`;
# the same, but with back quotes
passthru("ls");
# like system() but binary-safe
See also: proc_open()
[edit] PicoLisp
(call "ls")
[edit] Pike
int main(){
// This appears to only work in Pike >= 7.8 :(
string response = Process.run("ls");
// response is now a map containing 3 fields
// stderr, stdout, and exitcode. We want stdout.
write(response["stdout"] + "\n");
}
[edit] Pop11
The sysobey function runs commands using a shell:
sysobey('ls');
[edit] PowerShell
Since PowerShell is a shell, running commands is the default operation.
dir
ls
Get-ChildItem
are all equivalent (the first two are aliases for the third) but they are PowerShell-native commands. If one really needs to execute dir (which is no program but rather a built-in command in cmd.exe) this can be achieved by
cmd /c dir
[edit] Prolog
Works with: SWI Prolog
Works with: GNU Prolog
shell('ls').
[edit] PureBasic
ImportC "msvcrt.lib"
system(str.p-ascii)
EndImport
If OpenConsole()
system("dir & pause")
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
Input()
CloseConsole()
EndIf
[edit] Python
Works with: Python version 2.5
import os
code = os.system('ls') # Just execute the command, return a success/fail code
output = os.popen('ls').read() # If you want to get the output data. Deprecated.
or
Works with: Python version 2.4 (and above)
from subprocess import PIPE, Popen, STDOUT
p = Popen('ls', stdout=PIPE, stderr=STDOUT)
print p.communicate()[0]
Note: The latter is the preferred method for calling external processes, although cumbersome, it gives you finer control over the process.
or
Works with: Python version 2.2 (and above)
import commands
stat, out = commands.getstatusoutput('ls')
if not stat:
print out
[edit] R
system("ls")
[edit] Raven
Back tick string is auto executed:
`ls -la` as listing
Or specifically on any string:
'ls -la' shell as listing
[edit] REBOL
; Capture output to string variable:
x: "" call/output "dir" x
print x
; The 'console' refinement displays the command output on the REBOL command line.
call/console "dir *.r"
call/console "ls *.r"
call/console "pause"
; The 'shell' refinement may be necessary to launch some programs.
call/shell "notepad.exe"
[edit] REXX
Since REXX is a shell scripting language, it's easy to execute commands:
"dir /a:d"
[edit] Ruby
string = `ls`
# runs command and returns its STDOUT as a string
string = %x{ls}
# ditto, alternative syntax
system "ls"
# runs command and returns its exit status; its STDOUT gets output to our STDOUT
print `ls`
#The same, but with back quotes
exec "ls"
# replace current process with another
# call system command and read output asynchronously
io = IO.popen('ls')
# ... later
io.each {|line| puts line}
[edit] Slate
Run a command normally through the shell:
Platform run: 'ls'.
Run a command (this way takes advantage of the 'does not understand' message for the shell object and calls the Platform run: command above with a specific command):
shell ls: '*.slate'.
[edit] Smalltalk
Smalltalk system: 'ls'.
[edit] Standard ML
Just run the command:
OS.Process.system "ls"
[edit] Tcl
puts [exec ls]
This page uses "ls" as the primary example. For what it's worth, Tcl has built-in primitives for retrieving lists of files so one would rarely ever directly exec an ls command.
It is also possible to execute a system command by "open"ing it through a pipe from whence any output of the command can be read at any (later) time. For example:
set io [open "|ls" r]
would execute "ls" and pipe the result into the unit "io". From there one could receive it either line by line like this:
set nextline [gets $io]
or read the whole shebang in a fell swoop:
set lsoutput [read $io]
If the command is opened "rw", it is even possible to send it user input through the same handle, though care must be taken with buffering in that case.
[edit] Toka
needs shell
" ls" system
[edit] UNIX Shell
UNIX shells are designed to run system commands as a default operation.
ls
If one wants to capture the command's standard output:
CAPTUREDOUTPUT=$(ls)
In C-Shell this can be achieved by
set MYCMDOUTPUT = `ls`
echo $MYCMDOUTPUT
Where as in Korn Shell it becomes:
MYCMDOUTPUT=`ls`
echo $MYCMDOUTPUT
Note: in these last cases, C-Shell and Korn Shell, these are "backticks" rather than quotes or apostrophes. These "backticks" can also be used in Bourne compatible shells, though the $(...) form is preferred when discussing such things in e-mail, on USENET, or in other online forums (such as this wiki). Also the $(...) form of command substitution is nestable.
If one wishes to replace the shell process with some other command (chain into some command with no return) one can use the exec shell built-in command in any of the common UNIX shells (C-Shell, and all of the Bourne-compatible shells).
exec ls
[edit] Ursala
The library function, ask, parameterized by a shell descriptor, such as bash, spawns a process that interacts with that shell by feeding it a list of commands, and returns a transcript of the interaction.
Note that the output from the spawned process is captured and returned only, not sent to the standard output stream of the parent.
Here is a self-contained command line application providing a limited replacement for the ls command.
#import std
#import cli
#executable ('parameterized','')
myls = <.file$[contents: --<''>]>@hm+ (ask bash)/0+ -[ls --color=no]-!
The color option is needed to suppress terminal escape sequences.
[edit] Visual Basic
Shelling out a sub task in Visual Basic is rather a pain if you need to wait for the task to complete, which is probably the usual case. But it is possible.
Attribute VB_Name = "mdlShellAndWait"
Option Explicit
Private Declare Function OpenProcess Lib "kernel32" _
(ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, _
ByVal dwProcessId As Long) As Long
Private Declare Function GetExitCodeProcess Lib "kernel32" _
(ByVal hProcess As Long, lpExitCode As Long) As Long
Private Const STATUS_PENDING = &H103&
Private Const PROCESS_QUERY_INFORMATION = &H400
'
' Little function go get exit code given processId
'
Function ProcessIsRunning( processId as Long ) as Boolean
Dim exitCode as Long
Call GetExitCodeProcess(lProcessId, exitCode)
ProcessIsRunning = (exitCode = STATUS_PENDING)
End Function
' Spawn subprocess and wait for it to complete.
' I believe that the command in the command line must be an exe or a bat file.
' Maybe, however, it can reference any file the system knows how to "Open"
'
' commandLine is an executable.
' expectedDuration - is for poping up a dialog for whatever
' infoText - text for progressDialog dialog
Public Function ShellAndWait( commandLine As String, _
expectedDuration As Integer ) As Boolean
Dim inst As Long
Dim startTime As Long
Dim expirationTime As Long
Dim pid As Long
Dim expiresSameDay As Boolean
On Error GoTo HandleError
'Deal with timeout being reset at Midnight ($hitForBrains VB folks)
startTime = CLng(Timer)
expirationTime = startTime + expectedDuration
expiresSameDay = expirationTime < 86400
If Not expiresSameDay Then
expirationTime = expirationTime - 86400
End If
inst = Shell(commandLine, vbMinimizedNoFocus)
If inst <> 0 Then
pid = OpenProcess(PROCESS_QUERY_INFORMATION, False, inst)
Do While ProcessIsRunning( pid)
DoEvents
If Timer > expirationTime And (expiresSameDay Or Timer < startTime) Then
Exit Do
End If
Loop
ShellAndWait = True
Else
MsgBox ("Couldn't execute command: " & commandLine)
ShellAndWait = False
End If
Exit Function
HandleError:
MsgBox ("Couldn't execute command: " & commandLine)
ShellAndWait = False
End Function
Sub SpawnDir()
ShellAndWait("dir", 10)
End Sub

