Execute a system command: Difference between revisions
m →{{header|Objective-C}}: modernize |
Added zkl |
||
Line 1,425: | Line 1,425: | ||
=={{header|Wart}}== |
=={{header|Wart}}== |
||
<lang wart>system "ls"</lang> |
<lang wart>system "ls"</lang> |
||
=={{header|zkl}}== |
|||
<lang zkl>System.cmd(System.isWindows and "dir" or "ls")</lang> |
|||
=={{header|ZX Spectrum Basic}}== |
=={{header|ZX Spectrum Basic}}== |
Revision as of 08:09, 8 March 2014
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
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.
Ada
Using the IEEE POSIX Ada standard, P1003.5c: <lang ada>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;</lang>
Importing the C system() function: <lang 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;</lang>
Using the GNAT run-time library: <lang ada> 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; </lang>
Aikido
The simplest way to do this is using the system()
function. It returns a vector of strings (the output from the command).
<lang aikido>
var lines = system ("ls")
foreach line lines {
println (line)
}
</lang>
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;
<lang aikido>
exec ("ls")
</lang>
You also have the regular fork
and execv
calls available:
<lang aikido>
var pid = fork()
if (pid == 0) {
var args = ["/bin/ls"] execv ("/bin/ls", args) exit(1)
} var status = 0 waitpid (pid, status)
</lang>
Aime
<lang aime>sshell ss;
b_cast(ss_path(ss), "/bin/ls");
lf_p_text(ss_argv(ss), "ls");
o_text(ss_link(ss));</lang>
ALGOL 68
<lang algol68>system("ls")</lang>
Or the classic "!" shell escape can be implemented as an "!" operator:
<lang algol68>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</lang>
AppleScript
<lang applescript>do shell script "ls" without altering line endings</lang>
Applesoft BASIC
<lang ApplesoftBASIC>? CHR$(4)"CATALOG"</lang>
AutoHotkey
<lang autohotkey>Run, %comspec% /k dir & pause</lang>
AWK
<lang awk>BEGIN {
system("ls")
}</lang>
BASIC
<lang qbasic>SHELL "dir"</lang>
Batch file
<lang batch>dir</lang>
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. <lang bbcbasic>OSCLI "CAT"</lang>
With BBC BASIC for Windows you can execute the Windows dir command: <lang bbcbasic>OSCLI "*dir":REM *dir to bypass BB4W's built-in dir command</lang>
And if running BBC BASIC on a Unix host, you can execute the ls command: <lang bbcbasic>OSCLI "ls"</lang>
Bracmat
<lang bracmat>sys$dir</lang>
Brat
<lang brat>include :subprocess
p subprocess.run :ls #Lists files in directory</lang>
Brlcad
<lang brlcad> exec ls </lang>
C
ISO C & POSIX:
<lang c>#include <stdlib.h>
int main() {
system("ls"); return 0;
}</lang>
C++
<lang cpp>system("pause");</lang>
C#
Using Windows / .NET: <lang csharp>using System.Diagnostics;
namespace Execute {
class Program { static void Main(string[] args) { Process.Start("cmd.exe", "/c dir"); } }
}</lang>
<lang csharp>using System;
class Execute { static void Main() { System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.EnableRaisingEvents=false; proc.StartInfo.FileName="ls"; proc.Start(); } }</lang>
Clojure
<lang lisp>(.. Runtime getRuntime (exec "cmd /C dir"))</lang> <lang lisp>
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 } </lang>
<lang lisp> 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 </lang>
CMake
<lang cmake>execute_process(COMMAND ls)</lang>
Because of a quirk in the implementation (cmExecuteProcessCommand.cxx and ProcessUNIX.c), CMake diverts the standard output to a pipe. The effect is like running ls | 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.
<lang cmake># 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}")</lang>
-- pi is 3.1415926535897932384626433832795028841972
COBOL
<lang cobol>CALL "SYSTEM" USING BY CONTENT "ls"</lang>
CoffeeScript
<lang coffeescript> { spawn } = require 'child_process'
ls = spawn 'ls'
ls.stdout.on 'data', ( data ) -> console.log "Output: #{ data }"
ls.stderr.on 'data', ( data ) -> console.error "Error: #{ data }"
ls.on 'close', -> console.log "'ls' has finished executing." </lang>
Common Lisp
<lang lisp>(with-output-to-string (stream) (extensions:run-program "ls" nil :output stream))</lang>
<lang lisp>(system:call-system "ls")</lang>
<lang lisp>(trivial-shell:shell-command "ls")</lang>
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(). <lang d>std.process.system("ls");</lang>
dc
<lang dc>! ls</lang>
DCL
<lang DCL>Directory</lang> Or, shorter<lang DCL>dir</lang>
Delphi
<lang Delphi>program ExecuteSystemCommand;
{$APPTYPE CONSOLE}
uses Windows, ShellApi;
begin
ShellExecute(0, nil, 'cmd.exe', ' /c dir', nil, SW_HIDE);
end.</lang>
E
<lang 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`)
}</lang>
Erlang
<lang erlang>os:cmd("ls").</lang>
F#
<lang fsharp>System.Diagnostics.Process.Start("cmd", "/c dir")</lang>
Factor
<lang factor>"ls" run-process wait-for-process</lang>
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:
<lang fantom> class Main {
public static Void main () { p := Process (["ls"]) p.run }
} </lang>
Forth
<lang forth>s" ls" system</lang>
Fortran
The SYSTEM subroutine (and function) are a GNU extension. <lang fortran>program SystemTest
call system("ls")
end program SystemTest</lang>
Free Pascal
<lang Pascal>program ex01;
uses
SysUtils;
begin
ExecuteProcess('cmd', ' /c dir');
end.</lang>
Go
<lang 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))
}</lang>
gnuplot
<lang gnuplot>!ls</lang>
Groovy
<lang groovy>println "ls -la".execute().text</lang>
GUISS
<lang guiss>Start,Programs,Accessories,MSDOS Prompt,Type:dir[enter]</lang>
Haskell
<lang haskell>import System.Cmd
main = system "ls" </lang>
See also: the System.Process module
HicEst
<lang hicest>SYSTEM(CoMmand='pause') SYSTEM(CoMmand='dir & pause') </lang>
Icon and Unicon
The code below selects the 'ls' or 'dir' command at runtime based on the UNIX feature.
<lang Icon>procedure main()
write("Trying command ",cmd := if &features == "UNIX" then "ls" else "dir") system(cmd)
end</lang>
Unicon extends system to allow specification of files and a wait/nowait parameter as in the examples below. <lang Icon>
pid := system(command_string,&input,&output,&errout,"wait") pid := system(command_string,&input,&output,&errout,"nowait")
</lang>
IDL
<lang idl>$ls</lang>
Will execute "ls" with output to the screen.
<lang idl>spawn,"ls",result</lang>
will execute it and store the result in the string array "result".
<lang idl>spawn,"ls",unit=unit</lang>
will execute it asynchronously and direct any output from it into the LUN "unit" from whence it can be read at any (later) time.
Io
<lang io>System runCommand("ls") stdout println</lang>
J
The system command interface in J is provided by the standard "task" script: <lang j>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'</lang>
Java
<lang java5>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()); } }
}</lang>
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) <lang java>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) { } } } }
}</lang>
And the right way, which uses threading to read the InputStream given by the process. <lang java>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) { } } } }
}</lang>
JavaScript
JavaScript does not have any facilities to interact with the OS. However, host environments can provide this ability.
<lang javascript>var shell = new ActiveXObject("WScript.Shell"); shell.run("cmd /c dir & pause");</lang>
<lang javascript>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);</lang>
Joy
<lang joy>"ls" system.</lang>
K
Execute "ls" <lang K> \ls</lang>
Execute "ls" and capture the output in the variable "r": <lang K> r: 4:"ls"</lang>
Lang5
<lang Lang5>'ls system</lang>
Lasso
<lang Lasso>local( path = file_forceroot, ls = sys_process('/bin/ls', (:'-l', #path)), lswait = #ls -> wait )
'
' #ls -> read '
'</lang>
total 16 drwxr-xr-x 8 _lasso staff 272 Nov 10 08:13 mydir -rw-r--r-- 1 _lasso staff 38 Oct 29 16:05 myfile.lasso -rw-r--r--@ 1 _lasso staff 175 Oct 29 18:18 rosetta.lasso
Liberty BASIC
<lang lb>
drive1$ = left$(Drives$,1)
run "cmd.exe /";drive1$;" dir & pause"
</lang>
Limbo
There is no equivalent to Unix's exec() in Inferno per se; commands are just modules that have at least an init() function with the correct signature, and are loaded the same way as any other module. (As a result, there's nothing in the language or OS that prevents a program from acting as both a command and a library except convention.)
This version passes its argument list through to ls:
<lang Limbo>implement Runls;
include "sys.m"; sys: Sys; include "draw.m"; include "sh.m";
Runls: module { init: fn(ctxt: ref Draw->Context, args: list of string); };
init(ctxt: ref Draw->Context, args: list of string) { sys = load Sys Sys->PATH; ls := load Command "/dis/ls.dis"; if(ls == nil) die("Couldn't load /dis/ls.dis"); ls->init(ctxt, "ls" :: tl args); }
die(s: string) { sys->fprint(sys->fildes(2), "runls: %s: %r", s); raise "fail:errors"; }</lang>
It's not strictly necessary to pass the graphics context to ls, but it is generally a good idea to do so when calling another program.
Locomotive Basic
The Amstrad CPC464 uses a ROM based basic interpreter, so every statement within the program is a system command. If a command without a line number is typed, whilst the computer is in a ready state, the command gets executed immediately. There is no pause command, so in this example, we use the list command (which exhibits totally different behaviour to a pause command):
<lang basic>LIST</lang>
Logo
The lines of output of the SHELL command are returned as a list. <lang logo>print first butfirst shell [ls -a] ; ..</lang>
Lua
<lang 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</lang>
M4
<lang M4>syscmd(ifdef(`__windows__',`dir',`ls'))</lang>
Make
make can use system command in either definition of variables or in the targets
in definition
<lang make>contents=$(shell cat foo) curdir=`pwd`</lang>
in target
<lang make>mytarget:
cat foo | grep mytext</lang>
Mathematica
<lang Mathematica>Run["ls"]</lang>
MATLAB
To execute system commands in MATLAB, use the "system" keyword.
Sample Usage: <lang MATLAB>>> system('PAUSE')
Press any key to continue . . .
ans =
0
</lang>
Maxima
<lang>system("dir > list.txt")$</lang>
MAXScript
<lang maxscript>dosCommand "pause"</lang>
Mercury
<lang>
- - module execute_sys_cmd.
- - interface.
- - import_module io.
- - pred main(io::di, io::uo) is det.
- - implementation.
main(!IO) :-
io.call_system("ls", _Result, !IO).
</lang>
Modula-2
<lang modula2>MODULE tri;
FROM SYSTEM IMPORT ADR; FROM SysLib IMPORT system;
IMPORT TextIO, InOut, ASCII;
VAR fd : TextIO.File;
ch : CHAR;
PROCEDURE SystemCommand (VAR command : ARRAY OF CHAR) : BOOLEAN;
BEGIN
IF system (ADR (command) ) = 0 THEN RETURN TRUE ELSE RETURN FALSE END
END SystemCommand;
BEGIN
IF SystemCommand ("ls -1 tri.mod | ") = TRUE THEN InOut.WriteString ("No error reported.") ELSE InOut.WriteString ("Error reported!") END; LOOP InOut.Read (ch); InOut.Write (ch); IF ch < ' ' THEN EXIT END END; InOut.WriteLn; InOut.WriteBf
END tri.</lang>
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.
<lang modula3>UNSAFE MODULE Exec EXPORTS Main;
IMPORT Unix, M3toC;
VAR command := M3toC.CopyTtoS("ls");
BEGIN
EVAL Unix.system(command); M3toC.FreeCopiedS(command);
END Exec.</lang>
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: <lang MUMPS>Set X=$ZF(-1,"DIR")</lang>
In GT.M on OpenVMS, the following will work: <lang MUMPS>ZSY "DIR"</lang>
GT.M on UNIX is the same: <lang MUMPS>ZSY "ls"</lang>
Note: $ZF in GT.M is Unicode version of $F[ind].
NetRexx
<lang NetRexx>/* NetRexx */ options replace format comments java crossref symbols binary
import java.util.Scanner
runSample(arg) return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method runSample(arg) private static
parse arg command if command = then command = 'ls -oa' -- for Windows change to: 'cmd /C dir' do say 'Executing command:' command jprocess = Runtime.getRunTime().exec(command) jscanner = Scanner(jprocess.getInputStream()) loop label scanning while jscanner.hasNext() say jscanner.nextLine() end scanning catch ex = IOException ex.printStackTrace() end return
</lang>
Objective-C
NSTask runs an external process with explicit path and arguments. <lang objc>void runls() {
[[NSTask launchedTaskWithLaunchPath:@"/bin/ls" arguments:@[]] waitUntilExit];
}</lang> If you need to run a system command, invoke the shell: <lang objc>void runSystemCommand(NSString *cmd) {
[[NSTask launchedTaskWithLaunchPath:@"/bin/sh" arguments:@[@"-c", cmd]] waitUntilExit];
}</lang> Complete usage example:
<lang objc>#import <Foundation/Foundation.h>
void runSystemCommand(NSString *cmd) {
[[NSTask launchedTaskWithLaunchPath:@"/bin/sh" arguments:@[@"-c", cmd]] waitUntilExit];
}
int main(int argc, const char **argv) {
@autoreleasepool {
runSystemCommand(@"ls"); } return 0;
}</lang> Or use the C method above.
OCaml
Just run the command:
<lang ocaml>Sys.command "ls"</lang>
To capture the output of the command:
<lang ocaml>#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" ;;</lang>
a more complete version which also returns the contents from stderr, and checks the exit-status, and where the environment can be specified:
<lang ocaml>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)</lang>
val syscall : ?env:string array -> string -> string * string
Octave
<lang octave>system("ls");</lang>
Oz
<lang oz>{OS.system "ls" _}</lang>
A more sophisticated example can be found here.
PARI/GP
<lang parigp>system("ls")</lang>
Pascal
<lang pascal>Program ExecuteSystemCommand;
uses
SysUtils;
begin
ExecuteProcess('/bin/ls', '-alh');
end.</lang>
Perl
<lang 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</lang>
Also see: http://perldoc.perl.org/perlipc.html#Using-open()-for-IPC http://perldoc.perl.org/IPC/Open3.html
Perl 6
<lang perl6>run "ls" or die $!; # output to stdout
my @ls = qx/ls/; # output to variable
my $cmd = 'ls'; my @ls = qqx/$ls/; # same thing with interpolation</lang>
PDP-11 Assembly
PDP-11 running Unix <lang pdp-11>; Execute a file - the equivalent of system() in stdio
- On entry, r1=>nul-terminated command string
- On exit, VS=Couldn't fork
- VC=Forked successfully, r0=return value
.CLIsystem trap 2 ; fork() br CLIchild ; Child process returns here bcc CLIparent ; Parent process returns here mov (sp)+,r1 tst (sp)+ sev ; Couldn't fork, set V rts pc .CLIparent mov r0,-(sp) ; Save child's PID .CLIwait trap 7 ; wait() cmp r0,(sp) beq CLIfinished cmp r0,#&FFFF bne CLIwait ; Loop until child finished .CLIfinished tst (sp)+ ; Drop child's PID mov r1,r0 ; R0=return value mov (sp)+,r1 ; Restore R1 tst (sp)+ ; Drop original R0 swab r0 ; Move return value to bottom byte rts pc
- CLI child process
- -----------------
.CLIchild clr -(sp) ; end of string array mov r1,-(sp) ; => command string mov #UXsh3,-(sp) ; => "-c" mov #UXsh2,-(sp) ; => "sh" mov #&890B,TRAP_BUF ; exec mov #UXsh1,TRAP_BUF+2 ; => "/bin/sh" mov sp,TRAP_BUF+4 ; => pointers to command strings
- mov SV_ENVPTR,TRAP_BUF+6 ; => "PATH=etc"
trap 0 ; indir() EQUW TRAP_BUF ; exec(shell, parameters) add #8,sp ; If we get back, we didn't fork, we spawned mov (sp)+,r1 ; So, restore registers clr (sp)+ ; and return exit value in R0 rts pc
.UXsh1 EQUS "/bin/sh",0 .UXsh2 EQUS "sh",0 .UXsh3 EQUS "-c",0 ALIGN
.TRAP_BUF EQUW 0 EQUW 0 EQUW 0 EQUW 0</lang> So, call with, for example: <lang pdp-11>mov #cmd_ls,r1 ; => "ls" command string jsr pc,CLIsystem ... .cmd_ls EQUS "ls",0</lang>
PHP
The first line execute the command and the second line display the output: <lang php>@exec($command,$output); echo nl2br($output);</lang> Note:The '@' is here to prevent error messages to be displayed, 'nl2br' translate '\n' chars to 'br' in HTML.
Other: <lang php>$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</lang>
See also: proc_open()
PicoLisp
<lang PicoLisp>(call "ls")</lang>
Pike
<lang pike>int main(){
// Process.run was added in Pike 7.8 as a wrapper to simplify the use of Process.create_process() mapping response = Process.run("ls -l"); // response is now a map containing 3 fields // stderr, stdout, and exitcode. We want stdout. write(response["stdout"] + "\n");
// with older versions of pike it's a bit more complicated: Stdio.File stdout = Stdio.File(); Process.create_process(({"ls", "-l"}), ([ "stdout" : stdout->pipe() ]) ); write(stdout->read() + "\n");
}</lang>
Pop11
The sysobey function runs commands using a shell:
<lang pop11>sysobey('ls');</lang>
PowerShell
Since PowerShell is a shell, running commands is the default operation.
<lang powershell>dir
ls
Get-ChildItem</lang>
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
<lang powershell>cmd /c dir</lang>
Prolog
<lang prolog>shell('ls').</lang>
PureBasic
<lang PureBasic>ImportC "msvcrt.lib"
system(str.p-ascii)
EndImport
If OpenConsole()
system("dir & pause") Print(#CRLF$ + #CRLF$ + "Press ENTER to exit") Input() CloseConsole()
EndIf</lang>
Python
<lang python>import os exit_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.</lang> or
<lang python>import subprocess
- if the exit code was non-zero these commands raise a CalledProcessError
exit_code = subprocess.check_call(['ls', '-l']) # Python 2.5+ assert exit_code == 0 output = subprocess.check_output(['ls', '-l']) # Python 2.7+</lang>
or
<lang python>from subprocess import PIPE, Popen, STDOUT p = Popen('ls', stdout=PIPE, stderr=STDOUT) print p.communicate()[0]</lang>
Note: The latter is the preferred method for calling external processes, although cumbersome, it gives you finer control over the process.
or
<lang python>import commands stat, out = commands.getstatusoutput('ls') if not stat:
print out</lang>
R
<lang R>system("ls") output=system("ls",intern=TRUE)</lang>
Racket
<lang Racket>
- lang racket
- simple execution of a shell command
(system "ls")
- capture output
(string-split (with-output-to-string (λ() (system "ls"))) "\n")
- Warning
- passing random string to be run in a shell is a bad idea!
- much safer
- avoids shell parsing, arguments passed separately
(system* "/bin/ls" "-l")
- avoid specifying the executable path
(system* (find-executable-path "/bin/ls") "-l") </lang>
Raven
Back tick string is auto executed:
<lang raven>`ls -la` as listing</lang>
Or specifically on any string:
<lang raven>'ls -la' shell as listing</lang>
REBOL
<lang 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"</lang>
REXX
Since REXX is a shell scripting language, it's easy to execute commands: <lang REXX>"dir /a:d"</lang>
Ruby
<lang 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}</lang>
Run BASIC
<lang runbasic>print shell$("ls") ' prints the returned data from the OS a$ = shell$("ls") ' holds returned data in a$</lang>
Scala
<lang scala>import scala.sys.process.Process Process("ls", Seq("-oa"))!</lang>
Scheme
<lang scheme>(system "ls")</lang>
Seed7
System commands can make a program unportable. Unix, Linux and BSD use the command ls, while Windows respectively DOS use the command dir. The format written by ls respectively dir depends on operating system and locale. The library osfiles.s7i defines the function readDir, which reads the contents of a directory in a portable way. ReadDir works independend from operating system and locale and supports also Unicode filenames. Anyway, the task was to use a system command, so here is the example:
<lang seed7>$ include "seed7_05.s7i";
include "shell.s7i";
const proc: main is func
begin cmd_sh("ls"); end func;</lang>
Slate
Run a command normally through the shell:
<lang slate>Platform run: 'ls'.</lang>
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):
<lang slate>shell ls: '*.slate'.</lang>
Smalltalk
<lang smalltalk>Smalltalk system: 'ls'.</lang>
Standard ML
Just run the command:
<lang sml>OS.Process.system "ls"</lang>
Tcl
<lang tcl>puts [exec ls]</lang>
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:
<lang tcl>set io [open "|ls" r]</lang>
would execute "ls" and pipe the result into the channel whose name is put in the "io" variable. From there one could receive it either line by line like this:
<lang tcl>set nextline [gets $io]</lang>
or read the whole shebang in a fell swoop:
<lang tcl>set lsoutput [read $io]</lang>
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.
Toka
<lang toka>needs shell " ls" system</lang>
TUSCRIPT
<lang tuscript> $$ MODE TUSCRIPT system=SYSTEM () IF (system=="WIN") THEN EXECUTE "dir" ELSEIF (system.sw."LIN") THEN EXECUTE "ls -l" ENDIF </lang>
UNIX Shell
UNIX shells are designed to run system commands as a default operation. <lang bash>ls</lang>
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.
<lang bash>exec ls</lang>
Command substitution
One can also capture the command's standard output in a variable.
With Bourne Shell: <lang bash>output=`ls`</lang>
With Korn Shell or any modern shell: <lang bash>output=$(ls)</lang>
- Note 1: in
`ls`
, these are "backticks" rather than quotes or apostrophes. - Note 2: the $(...) form works in all modern shells, including the Almquist Shell, Bash and any POSIX shell.
- The old `backticks` can also be used in the newer shells, but their users prefer the $(...) form when discussing such things in e-mail, on USENET, or in other online forums (such as this wiki). The only reason to use `backticks` is in scripts for old Bourne Shell.
The `...` form is difficult to nest, but the $(...) form is very nestable.
<lang bash>output=`expr \`echo hi | wc -c\` - 1` output=$(expr $(echo hi | wc -c) - 1)</lang>
Both forms, `backticks` and $(...), also work inside double-quoted strings. This prevents file name expansion and also prevents word splitting.
<lang bash>echo "Found: `grep 80/tcp /etc/services`" echo "Found: $(grep 80/tcp /etc/services)"</lang>
C Shell
C Shell also runs system commands, and has an exec built-in command, exactly like Bourne Shell.
<lang csh>ls # run command, return to shell exec ls # replace shell with command</lang>
`Backticks` are slightly different. When inside double quotes, as "`...`", C Shell splits words at newlines, like "line 1" "line 2" ..., but preserves spaces and tabs.
<lang csh>set output=( "`grep 80/ /etc/services`" ) echo "Line 1: $output[1]" echo "Line 2: $output[2]"</lang>
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. <lang Ursala>#import std
- import cli
- executable ('parameterized',)
myls = <.file$[contents: --<>]>@hm+ (ask bash)/0+ -[ls --color=no]-!</lang> The color option is needed to suppress terminal escape sequences.
Vedit macro language
<lang vedit>system("dir", DOS)</lang>
The above does not work on 64-bit Windows versions which do not have 16-bit DOS emulation. In this case, you need to call cmd.exe explicitly:
<lang vedit>system('cmd /k "dir"')</lang>
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. <lang vb>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</lang>
Wart
<lang wart>system "ls"</lang>
zkl
<lang zkl>System.cmd(System.isWindows and "dir" or "ls")</lang>
ZX Spectrum Basic
The ZX Spectrum uses a ROM based basic interpreter, so every statement within the program is a system command. If a command without a line number is typed, whilst the computer is in a ready state, the command gets executed immediately:
<lang zxbasic>PAUSE 100</lang>
- Programming Tasks
- Programming environment operations
- Ada
- Aikido
- Aime
- ALGOL 68
- AppleScript
- Applesoft BASIC
- AutoHotkey
- AWK
- BASIC
- Batch file
- BBC BASIC
- Bracmat
- Brat
- Brlcad
- C
- C++
- C sharp
- Clojure
- CMake
- COBOL
- CoffeeScript
- Common Lisp
- Trivial-shell
- D
- Dc
- DCL
- Delphi
- E
- Erlang
- F Sharp
- Factor
- Fantom
- Forth
- Fortran
- Free Pascal
- Go
- Gnuplot
- Groovy
- GUISS
- Haskell
- HicEst
- Icon
- Unicon
- IDL
- Io
- J
- Java
- JavaScript
- Joy
- K
- Lang5
- Lasso
- Liberty BASIC
- Limbo
- Locomotive Basic
- Logo
- Lua
- M4
- Make
- Mathematica
- MATLAB
- Maxima
- MAXScript
- Mercury
- Modula-2
- Modula-3
- MUMPS
- NetRexx
- Objective-C
- OCaml
- Octave
- Oz
- PARI/GP
- Pascal
- SysUtils
- Perl
- Perl 6
- PDP-11 Assembly
- PHP
- PicoLisp
- Pike
- Pop11
- PowerShell
- Prolog
- PureBasic
- Python
- R
- Racket
- Raven
- REBOL
- REXX
- Ruby
- Run BASIC
- Scala
- Scheme
- Seed7
- Slate
- Smalltalk
- Standard ML
- Tcl
- Toka
- TUSCRIPT
- UNIX Shell
- C Shell
- Ursala
- Vedit macro language
- Visual Basic
- Wart
- Zkl
- ZX Spectrum Basic
- Retro/Omit
- TI-83 BASIC/Omit
- TI-89 BASIC/Omit