http://rosettacode.org/wiki/Execute_a_System_Command
Contents
- 1
Ada - 2
Aikido - 3
Aime - 4
ALGOL 68 - 5
AppleScript - 6
AutoHotkey - 7
AWK - 8
BASIC - 9
BBC BASIC - 10
Bracmat - 11
Brat - 12
Brlcad - 13
C - 14
C++ - 15
C# - 16
Clojure - 17
CMake - 18
Common Lisp - 19
D - 20
dc - 21
DCL - 22
Delphi - 23
E - 24
Erlang - 25
Factor - 26
Fantom - 27
Forth - 28
Fortran - 29
Go - 30
gnuplot - 31
GUISS - 32
Haskell - 33
HicEst - 34
Icon and Unicon - 35
IDL - 36
Io - 37
J - 38
Java - 39
JavaScript - 40
Joy - 41
K - 42
Liberty BASIC - 43
Locomotive Basic - 44
Logo - 45
Lua - 46
M4 - 47
Make - 48
Mathematica - 49
MATLAB - 50
Maxima - 51
MAXScript - 52
Mercury - 53
Modula-2 - 54
Modula-3 - 55
MUMPS - 56
Objective-C - 57
OCaml - 58
Octave - 59
Oz - 60
PARI/GP - 61
Pascal - 62
Perl - 63
Perl 6 - 64
PHP - 65
PicoLisp - 66
Pike - 67
Pop11 - 68
PowerShell - 69
Prolog - 70
PureBasic - 71
Python - 72
R - 73
Raven - 74
REBOL - 75
REXX - 76
Ruby - 77
Run BASIC - 78
Scala - 79
Scheme - 80
Seed7 - 81
Slate - 82
Smalltalk - 83
Standard ML - 84
Tcl - 85
Toka - 86
TUSCRIPT - 87
UNIX Shell - 88
Ursala - 89
Vedit macro language - 90
Visual Basic - 91
ZX Spectrum Basic
Ada
Using the IEEE POSIX Ada standard, P1003.5c:
with POSIX.Unsafe_Process_Primitives; procedure Execute_A_System_Command is Arguments : POSIX.POSIX_String_List; begin POSIX.Append (Arguments, "ls"); POSIX.Unsafe_Process_Primitives.Exec_Search ("ls", Arguments); end Execute_A_System_Command;
Importing the C system() function:
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;
Using the GNAT run-time library:
with Ada.Text_IO; use Ada.Text_IO; with System.OS_Lib; use System.OS_Lib; procedure Execute_Synchronously is Result : Integer; Arguments : Argument_List := ( 1=> new String'("cmd.exe"), 2=> new String'("/C dir c:\temp\*.adb") ); begin Spawn ( Program_Name => "cmd.exe", Args => Arguments, Output_File_Descriptor => Standout, Return_Code => Result ); for Index in Arguments'Range loop Free (Arguments (Index)); -- Free the argument list end loop; end Execute_Synchronously;
[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]Aime
sshell ss; b_cast(ss_path(ss), "/bin/ls"); lf_p_text(ss_argv(ss), "ls"); o_text(ss_link(ss));
[edit]ALGOL
68
system("ls")
Or the classic "!" shell escape can be implemented as an "!" operator:
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]BBC
BASIC
On Acorn computers the *CAT command catalogues the current directory, the equivalent of the Unix ls command or the DOS/Windows dir command. The BBC BASIC OSCLI command passes a string to the Command Line Interpreter to execute a system command, it is the
equivalent of C's system() command.
OSCLI "CAT"
With BBC BASIC for Windows you can execute the Windows dir command:
OSCLI "*dir":REM *dir to bypass BB4W's built-in dir command
And if running BBC BASIC on a Unix host, you can execute the ls command:
OSCLI "ls"
[edit]Bracmat
sys$dir
[edit]Brat
include :subprocess p subprocess.run :ls #Lists files in directory
[edit]Brlcad
exec ls
[edit]C
ISO C & POSIX:
#include <stdlib.h> int main() { system("ls"); return 0; }
[edit]C++
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"); } } }
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"))
user=> (use '[clojure.java.shell :only [sh]]) user=> (sh "ls" "-aul") {:exit 0, :out total 64 drwxr-xr-x 11 zkim staff 374 Jul 5 13:21 . drwxr-xr-x 25 zkim staff 850 Jul 5 13:02 .. drwxr-xr-x 12 zkim staff 408 Jul 5 13:02 .git -rw-r--r-- 1 zkim staff 13 Jul 5 13:02 .gitignore -rw-r--r-- 1 zkim staff 12638 Jul 5 13:02 LICENSE.html -rw-r--r-- 1 zkim staff 4092 Jul 5 13:02 README.md drwxr-xr-x 2 zkim staff 68 Jul 5 13:15 classes drwxr-xr-x 5 zkim staff 170 Jul 5 13:15 lib -rw-r--r--@ 1 zkim staff 3396 Jul 5 13:03 pom.xml -rw-r--r--@ 1 zkim staff 367 Jul 5 13:15 project.clj drwxr-xr-x 4 zkim staff 136 Jul 5 13:15 src , :err }
user=> (use '[clojure.java.shell :only [sh]]) user=> (println (:out (sh "cowsay" "Printing a command-line output"))) _________________________________ < Printing a command-line output. > --------------------------------- \ ^__^ \ (oo)\_______ (__)\ )\/\ ||----w | || || nil
[edit]CMake
execute_process(COMMAND ls)
Because of a quirk in the implementation (cmExecuteProcessCommand.cxx andProcessUNIX.c),
CMake diverts the standard output to a pipe. The effect is like runningls | cat
in the shell. The
ls process inherits the original standard input and standard error, but receives a new pipe for standard output. CMake then reads this pipe and copies all data to the original standard output.
execute_process() can also chain commands in a pipeline, and capture output.
# Calculate pi to 40 digits after the decimal point. execute_process( COMMAND printf "scale = 45; 4 * a(1) + 5 / 10 ^ 41\\n" COMMAND bc -l COMMAND sed -e "s/.\\{5\\}$//" OUTPUT_VARIABLE pi OUTPUT_STRIP_TRAILING_WHITESPACE) message(STATUS "pi is ${pi}")
-- pi is 3.1415926535897932384626433832795028841972
[edit]Common
Lisp
(with-output-to-string (stream) (extensions:run-program "ls" nil :output stream))
(system:call-system "ls")
(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
Directory
Or, shorter
dir
[edit]Delphi
program ExecuteSystemCommand; {$APPTYPE CONSOLE} uses Windows, ShellApi; begin ShellExecute(0, nil, 'cmd.exe', ' /c dir', nil, SW_HIDE); end.
[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]Fantom
The Process class handles creating and running external processes. in/out/err streams can be redirected, but default to the usual stdin/stdout/stderr. So following program prints result of 'ls' to the command line:
class Main { public static Void main () { p := Process (["ls"]) p.run } }
[edit]Forth
s" ls" system
[edit]Fortran
The SYSTEM subroutine (and function) are a GNU extension.
program SystemTest call system("ls") end program SystemTest
[edit]Go
package main import "fmt" import "os/exec" func main() { cmd := exec.Command("ls", "-l") output, err := cmd.Output() if (err != nil) { fmt.Println(err) return } fmt.Print(string(output)) }
[edit]gnuplot
!ls
[edit]GUISS
Start,Programs,Accessories,MSDOS Prompt,Type:dir[enter]
[edit]Haskell
import System.Cmd main = system "ls"
See also: the
System.Process module
[edit]HicEst
SYSTEM(CoMmand='pause') SYSTEM(CoMmand='dir & pause')
[edit]Icon
andUnicon
The code below selects the 'ls' or 'dir' command at runtime based on the UNIX feature.
procedure main() write("Trying command ",cmd := if &features == "UNIX" then "ls" else "dir") system(cmd) end
Unicon extends system to allow specification of files and a wait/nowait parameter as in the examples below.
pid := system(command_string,&input,&output,&errout,"wait") pid := system(command_string,&input,&output,&errout,"nowait")
[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
System runCommand("ls") stdout println
[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
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()); } } }
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);