Execute a system command: Difference between revisions

m
(VB.Net system command execution)
m (→‎{{header|Wren}}: Minor tidy)
(46 intermediate revisions by 24 users not shown)
Line 9:
 
=={{header|11l}}==
<syntaxhighlight lang ="11l">os:(‘pause’)</langsyntaxhighlight>
 
=={{header|ABAP}}==
ABAP report which checks if there is an external command called 'ls' for the os of the current application server. When running on Windows, it calls dir, for all other platforms ls. A new command is created if not existing and run.
 
<langsyntaxhighlight lang="abap">*&---------------------------------------------------------------------*
*& Report ZEXEC_SYS_CMD
*&
Line 147:
ENDIF.
ENDIF.
ENDIF.</langsyntaxhighlight>
 
=={{header|Ada}}==
Using the IEEE POSIX Ada standard, P1003.5c:
<langsyntaxhighlight lang="ada">with POSIX.Unsafe_Process_Primitives;
 
procedure Execute_A_System_Command is
Line 158:
POSIX.Append (Arguments, "ls");
POSIX.Unsafe_Process_Primitives.Exec_Search ("ls", Arguments);
end Execute_A_System_Command;</langsyntaxhighlight>
 
Importing the C system() function:
<langsyntaxhighlight lang="ada">with Interfaces.C; use Interfaces.C;
 
procedure Execute_System is
Line 169:
begin
Ret_Val := Sys(To_C("ls"));
end Execute_System;</langsyntaxhighlight>
 
Using the GNAT run-time library:
<langsyntaxhighlight lang="ada">
with Ada.Text_IO; use Ada.Text_IO;
with System.OS_Lib; use System.OS_Lib;
Line 193:
end loop;
end Execute_Synchronously;
</syntaxhighlight>
</lang>
 
=={{header|Aikido}}==
The simplest way to do this is using the <code>system()</code> function. It returns a vector of strings (the output from the command).
<langsyntaxhighlight lang="aikido">
var lines = system ("ls")
foreach line lines {
println (line)
}
</syntaxhighlight>
</lang>
If you don't want to process the output you can use the <code>exec</code> function. It writes the output to the standard output stream by default;
<langsyntaxhighlight lang="aikido">
exec ("ls")
</syntaxhighlight>
</lang>
You also have the regular <code>fork</code> and <code>execv</code> calls available:
<langsyntaxhighlight lang="aikido">
var pid = fork()
if (pid == 0) {
Line 218:
waitpid (pid, status)
 
</syntaxhighlight>
</lang>
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">sshell ss;
 
ss.argv.insert("ls");
 
o_(ss.link);
</syntaxhighlight>
</lang>
 
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9 - "system" is not part of the standard's prelude.}}
<langsyntaxhighlight lang="algol68">system("ls")</langsyntaxhighlight>
 
Or the classic "!" shell escape can be implemented as an "!" operator:
 
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9 - "system" & "ANDF" are not part of the standard's prelude.}}
<langsyntaxhighlight 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</langsyntaxhighlight>
 
 
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="amazing hopper">
#!/usr/bin/hopper
 
#include <hopper.h>
 
main:
 
/* execute "ls -lstar" with no result return (only displayed) */
{"ls -lstar"},execv
/* this form does not allow composition of the line with variables.
Save result in the variable "s", and then display it */
s=`ls -l | awk '{if($2=="2")print $0;}'`
{"\n",s,"\n"}print
data="2"
{""}tok sep
 
// the same as above, only I can compose the line:
{"ls -l | awk '{if($2==\"",data,"\")print $0;}'"}join(s),{s}exec,print
{"\n\n"}print
// this does the same as above, with an "execute" macro inside a "let" macro:
t=0,let (t := execute( {"ls -l | awk '{if($2==\""},{data},{"\")print $0;}'"} ))
{t,"\n"}print
 
{0}return
</syntaxhighlight>
 
=={{header|APL}}==
<syntaxhighlight lang="apl">
∇ system s;handle
⍝⍝ NOTE: one MUST give the full absolute path to the program (eg. /bin/ls)
⍝⍝ Exercise: Can you improve this by parsing the value of
⍝⍝ ⎕ENV 'PATH' ?
⍝⍝
handle ← ⎕fio['fork_daemon'] s
⎕fio['fclose'] handle
system '/bin/ls /var'
backups games lib lock mail run tmp
cache gemini local log opt spool
</syntaxhighlight>
 
=={{header|AppleScript}}==
<langsyntaxhighlight lang="applescript">do shell script "ls" without altering line endings</langsyntaxhighlight>
 
=={{header|Applesoft BASIC}}==
<langsyntaxhighlight ApplesoftBASIClang="applesoftbasic">? CHR$(4)"CATALOG"</langsyntaxhighlight>
 
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">print execute "ls"</syntaxhighlight>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang="autohotkey">Run, %comspec% /k dir & pause</langsyntaxhighlight>
 
=={{header|AutoIt}}==
<langsyntaxhighlight AutoItlang="autoit">Run(@ComSpec & " /c " & 'pause', "", @SW_HIDE)</langsyntaxhighlight>
 
=={{header|AWK}}==
 
Using system() function:
<langsyntaxhighlight lang="awk">BEGIN {
system("ls") # Unix
#system("dir") # DOS/MS-Windows
}</langsyntaxhighlight>
 
Using getline command:
<langsyntaxhighlight lang="awk">BEGIN {
ls = sys2var("ls")
print ls
Line 274 ⟶ 325:
close(command)
return ship
}</langsyntaxhighlight>
 
=={{header|BASIC}}==
 
<langsyntaxhighlight lang="qbasic">SHELL "dir"</langsyntaxhighlight>
 
==={{header|BaCon}}===
<langsyntaxhighlight lang="freebasic">' Execute a system command
SYSTEM "ls"</langsyntaxhighlight>
 
=={{header|BASIC256}}==
<syntaxhighlight lang="basic256">system "dir"</syntaxhighlight>
 
=={{header|Batch File}}==
 
<syntaxhighlight lang ="batch">dir</langsyntaxhighlight>
 
=={{header|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.
<langsyntaxhighlight lang="bbcbasic">OSCLI "CAT"</langsyntaxhighlight>
 
With BBC BASIC for Windows you can execute the Windows dir command:
<langsyntaxhighlight lang="bbcbasic">OSCLI "*dir":REM *dir to bypass BB4W's built-in dir command</langsyntaxhighlight>
 
And if running BBC BASIC on a Unix host, you can execute the ls command:
<langsyntaxhighlight lang="bbcbasic">OSCLI "ls"</langsyntaxhighlight>
 
=={{header|Befunge}}==
{{works with|Befunge|98}}
Works with any Funge-98 on Unix, try https://tio.run/##S0pNK81LT9W1tNAtqAQz//9XKs5RsnX4/x8A
<syntaxhighlight lang="befunge">"sl"=@;pushes ls, = executes it, @ ends it;</syntaxhighlight>
 
 
=={{header|BQN}}==
 
<code>•SH</code> is a function defined in the BQN spec, which provides output from a shell command.
 
The arguments to <code>•SH</code> are the command, followed by its arguments as a flat list of strings. For example:
<syntaxhighlight lang="bqn">•SH ⟨"ls"⟩</syntaxhighlight>
 
Will give an output as a list of three elements: the command's exit code, text written to stdout, and text written to stderr.
 
=={{header|Bracmat}}==
<syntaxhighlight lang ="bracmat">sys$dir</langsyntaxhighlight>
 
=={{header|Brat}}==
<langsyntaxhighlight lang="brat">include :subprocess
 
p subprocess.run :ls #Lists files in directory</langsyntaxhighlight>
 
=={{header|Brlcad}}==
 
<langsyntaxhighlight lang="brlcad">
exec ls
</syntaxhighlight>
</lang>
 
=={{header|C}}==
ISO C & POSIX:
 
<langsyntaxhighlight lang="c">#include <stdlib.h>
 
int main()
Line 321 ⟶ 390:
system("ls");
return 0;
}</langsyntaxhighlight>
 
=={{header|C++}}==
{{works with|Visual C++|2005}}
<lang cpp>system("pause");</lang>
 
=={{header|C sharp|C#}}==
Using Windows / .NET:
<langsyntaxhighlight lang="csharp">using System.Diagnostics;
 
namespace Execute
Line 340 ⟶ 405:
}
}
}</langsyntaxhighlight>
 
{{works with|MCS|1.2.3.1}}
<langsyntaxhighlight lang="csharp">using System;
class Execute {
Line 352 ⟶ 417:
proc.Start();
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
{{works with|Visual C++|2005}}
<syntaxhighlight lang="cpp">system("pause");</syntaxhighlight>
 
=={{header|Clojure}}==
 
<langsyntaxhighlight lang="lisp">(.. Runtime getRuntime (exec "cmd /C dir"))</langsyntaxhighlight>
<langsyntaxhighlight lang="lisp">
 
user=> (use '[clojure.java.shell :only [sh]])
Line 376 ⟶ 446:
drwxr-xr-x 4 zkim staff 136 Jul 5 13:15 src
, :err }
</syntaxhighlight>
</lang>
 
<langsyntaxhighlight lang="lisp">
user=> (use '[clojure.java.shell :only [sh]])
 
Line 393 ⟶ 463:
 
nil
</syntaxhighlight>
</lang>
 
=={{header|CMake}}==
{{works with|Unix}}
<syntaxhighlight lang ="cmake">execute_process(COMMAND ls)</langsyntaxhighlight>
 
Because of a quirk in the implementation ([http://cmake.org/gitweb?p=cmake.git;a=blob;f=Source/cmExecuteProcessCommand.cxx;hb=HEAD cmExecuteProcessCommand.cxx] and [http://cmake.org/gitweb?p=cmake.git;a=blob;f=Source/kwsys/ProcessUNIX.c;hb=HEAD ProcessUNIX.c]), CMake diverts the standard output to a pipe. The effect is like running <code>ls | cat</code> 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.
Line 403 ⟶ 473:
''execute_process()'' can also chain commands in a pipeeline, and capture output.
 
<langsyntaxhighlight lang="cmake"># Calculate pi to 40 digits after the decimal point.
execute_process(
COMMAND printf "scale = 45; 4 * a(1) + 5 / 10 ^ 41\\n"
Line 409 ⟶ 479:
COMMAND sed -e "s/.\\{5\\}$//"
OUTPUT_VARIABLE pi OUTPUT_STRIP_TRAILING_WHITESPACE)
message(STATUS "pi is ${pi}")</langsyntaxhighlight>
 
<pre>-- pi is 3.1415926535897932384626433832795028841972</pre>
Line 415 ⟶ 485:
=={{header|COBOL}}==
{{works with|OpenCOBOL}}
<langsyntaxhighlight lang="cobol">CALL "SYSTEM" USING BY CONTENT "ls"</langsyntaxhighlight>
 
=={{header|CoffeeScript}}==
{{works with|Node.js}}
<langsyntaxhighlight lang="coffeescript">
{ spawn } = require 'child_process'
 
Line 429 ⟶ 499:
 
ls.on 'close', -> console.log "'ls' has finished executing."
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
{{works with|CMUCL}}
<langsyntaxhighlight lang="lisp">(with-output-to-string (stream) (extensions:run-program "ls" nil :output stream))</langsyntaxhighlight>
 
{{works with|LispWorks}}
 
<langsyntaxhighlight lang="lisp">(system:call-system "ls")</langsyntaxhighlight>
 
{{libheader|trivial-shell}}
 
<langsyntaxhighlight lang="lisp">(trivial-shell:shell-command "ls")</langsyntaxhighlight>
 
{{libheader|uiop}}
 
<syntaxhighlight lang="lisp">; uiop is part of the de facto build system, asdf, so should be available to most installations.
 
; synchronous
(uiop:run-program "ls")
 
; async
(defparameter *process* (uiop:launch-program "ls"))
(uiop:wait-process *process*)</syntaxhighlight>
 
=={{header|D}}==
<syntaxhighlight lang="d">
<lang d>
import std.process, std.stdio;
//these two alternatives wait for the process to return, and capture the output
Line 454 ⟶ 535:
writeln((ls_array.status == 0) ? ls_array.output : "command failed");
//other alternatives exist to spawn processes in parallel and capture output via pipes
</syntaxhighlight>
</lang>
std.process.system() is deprecated.
 
=={{header|dc}}==
<syntaxhighlight lang ="dc">! ls</langsyntaxhighlight>
 
 
=={{header|DBL}}==
<syntaxhighlight lang="dbl">XCALL SPAWN ("ls *.jpg > file.txt") ;execute command and continue
XCALL EXEC ("script.sh") ;execute script or binary and exit
STOP '@/bin/ls *.jpg > file.txt' ;exit and execute command</syntaxhighlight>
 
=={{header|DCL}}==
<syntaxhighlight lang DCL="dcl">Directory</langsyntaxhighlight>
Or, shorter<syntaxhighlight lang DCL="dcl">dir</langsyntaxhighlight>
 
=={{header|Delphi}}==
<langsyntaxhighlight Delphilang="delphi">program ExecuteSystemCommand;
 
{$APPTYPE CONSOLE}
Line 472 ⟶ 560:
begin
ShellExecute(0, nil, 'cmd.exe', ' /c dir', nil, SW_HIDE);
end.</langsyntaxhighlight>
 
=={{header|E}}==
<langsyntaxhighlight lang="e">def ls := makeCommand("ls")
ls("-l")
 
Line 484 ⟶ 572:
} catch problem {
print(`failed to execute ls: $problem`)
}</langsyntaxhighlight>
 
=={{header|Emacs Lisp}}==
===Syncronous===
<lang Lisp>(shell-command "ls")</lang>
 
Synchronously (shell, interactive):
===Asyncronous===
 
<lang Lisp>(async-shell-command "ls")</lang>
<syntaxhighlight lang="lisp">(shell-command "ls")</syntaxhighlight>
 
Asynchronously (shell, interactive):
 
<syntaxhighlight lang="lisp">(async-shell-command "ls")</syntaxhighlight>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">os:cmd("ls").</langsyntaxhighlight>
 
=={{header|ERRE}}==
Line 501 ⟶ 592:
For example
 
<syntaxhighlight lang="text"> SHELL("DIR/W")</langsyntaxhighlight>
 
lists the current directory and then returns to the program.
 
<langsyntaxhighlight ERRElang="erre">cmd$="DIR/W"
SHELL(cmd$)</langsyntaxhighlight>
 
=={{header|Euphoria}}==
Euphoria has 2 systems command functions: '''system()''' and '''system_exec()'''.
<langsyntaxhighlight lang="euphoria"> -- system --
-- the simplest way --
-- system spawns a new shell so I/O redirection is possible --
Line 541 ⟶ 632:
else
printf( STDERR, "command %s failed with code %d\n", ls_command, exit_code)
end if</langsyntaxhighlight>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">System.Diagnostics.Process.Start("cmd", "/c dir")</langsyntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">"ls" run-process wait-for-process</langsyntaxhighlight>
 
=={{header|Fantom}}==
Line 553 ⟶ 644:
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:
 
<langsyntaxhighlight lang="fantom">
class Main
{
Line 562 ⟶ 653:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Forth}}==
{{works with|gforth|0.6.2}}
<langsyntaxhighlight lang="forth">s" ls" system</langsyntaxhighlight>
 
=={{header|Fortran}}==
execute_command_line subroutine in Fortran 2008 and later runs a system command
<langsyntaxhighlight lang="fortran">
program SystemTest
integer :: i
call execute_command_line ("ls", exitstat=i)
end program SystemTest
</syntaxhighlight>
</lang>
 
{{works with|gfortran}}
The <tt>SYSTEM</tt> subroutine (and function) are a GNU extension.
<langsyntaxhighlight lang="fortran">program SystemTest
call system("ls")
end program SystemTest</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Shell "dir"
Sleep</langsyntaxhighlight>
 
=={{header|Frink}}==
<langsyntaxhighlight lang="frink">r = callJava["java.lang.Runtime", "getRuntime"]
println[read[r.exec["dir"].getInputStream[]]]</langsyntaxhighlight>
 
=={{header|FunL}}==
<langsyntaxhighlight lang="funl">import sys.execute
 
execute( if $os.startsWith('Windows') then 'dir' else 'ls' )</langsyntaxhighlight>
 
=={{header|FutureBasic}}==
FB 7.0.23+
This simple example prints the output to a console window. With its open "Unix" command, FB has robust capability as a system interface to the Free BSD Unix core of Macintosh OS X 10.x.
<langsyntaxhighlight lang="futurebasic">
print unix(@"ls -A")
include "ConsoleWindow"
</syntaxhighlight>
 
Classic FB using Pascal strings
<syntaxhighlight>
local fn DoUnixCommand( cmd as str255 )
dim as str255 s
 
open "Unix", 2, cmd
Line 615 ⟶ 708:
 
fn DoUnixCommand( "ls -A" )
</syntaxhighlight>
</lang>
 
Output:
Line 644 ⟶ 737:
usr
var
</pre>
 
Modern FB using CFStrings
<syntaxhighlight>
 
include "NSLog.incl"
 
// For remote uses like curl
// #plist NSAppTransportSecurity @{NSAllowsArbitraryLoads:YES}
 
local fn RunTerminalCommand( cmd as CFStringRef ) as CFStringRef
————————————————————————————————————————————————————————————————————————————————————————————————————
ErrorRef err = NULL
CFStringRef outputStr = NULL
TaskRef task = fn TaskInit
TaskSetExecutableURL( task, fn URLFileURLWithPath( @"/bin/zsh" ) )
CFStringRef cmdStr = fn StringWithFormat( @"%@", cmd )
CFArrayRef args = fn ArrayWithObjects( @"-c", cmdStr, NULL )
TaskSetArguments( task, args )
PipeRef p = fn PipeInit
TaskSetStandardOutput( task, p )
TaskSetStandardError( task, p )
FileHandleRef fh = fn PipeFileHandleForReading( p )
fn TaskLaunch( task, NULL )
TaskWaitUntilExit( task )
CFDataRef dta = fn FileHandleReadDataToEndOfFile( fh, @err )
if err then NSLog( @"Error reading file: %@", fn ErrorLocalizedDescription( err ) ) : exit fn
fn FileHandleClose( fh, @err )
if err then NSLog( @"Error closing file: %@", fn ErrorLocalizedDescription( err ) ) : exit fn
outputStr = fn StringWithData( dta, NSUTF8StringEncoding )
end fn = outputStr
 
CFStringRef cmd
 
cmd = @"cal 2023"
NSLog( @"%@", fn RunTerminalCommand( cmd ) )
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
2023
January February March
Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
1 2 3 4 5 6 7 1 2 3 4 1 2 3 4
8 9 10 11 12 13 14 5 6 7 8 9 10 11 5 6 7 8 9 10 11
15 16 17 18 19 20 21 12 13 14 15 16 17 18 12 13 14 15 16 17 18
22 23 24 25 26 27 28 19 20 21 22 23 24 25 19 20 21 22 23 24 25
29 30 31 26 27 28 26 27 28 29 30 31
 
April May June
Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
1 1 2 3 4 5 6 1 2 3
2 3 4 5 6 7 8 7 8 9 10 11 12 13 4 5 6 7 8 9 10
9 10 11 12 13 14 15 14 15 16 17 18 19 20 11 12 13 14 15 16 17
16 17 18 19 20 21 22 21 22 23 24 25 26 27 18 19 20 21 22 23 24
23 24 25 26 27 28 29 28 29 30 31 25 26 27 28 29 30
30
 
July August September
Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
1 1 2 3 4 5 1 2
2 3 4 5 6 7 8 6 7 8 9 10 11 12 3 4 5 6 7 8 9
9 10 11 12 13 14 15 13 14 15 16 17 18 19 10 11 12 13 14 15 16
16 17 18 19 20 21 22 20 21 22 23 24 25 26 17 18 19 20 21 22 23
23 24 25 26 27 28 29 27 28 29 30 31 24 25 26 27 28 29 30
30 31
 
October November December
Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
1 2 3 4 5 6 7 1 2 3 4 1 2
8 9 10 11 12 13 14 5 6 7 8 9 10 11 3 4 5 6 7 8 9
15 16 17 18 19 20 21 12 13 14 15 16 17 18 10 11 12 13 14 15 16
22 23 24 25 26 27 28 19 20 21 22 23 24 25 17 18 19 20 21 22 23
29 30 31 26 27 28 29 30 24 25 26 27 28 29 30
31
</pre>
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=9460b39a86794a7346a390aeb50fc5cf Click this link to run this code]'''
<langsyntaxhighlight lang="gambas">Public Sub Main()
 
Shell "ls -aul"
 
End</langsyntaxhighlight>
Output:
<pre>
Line 666 ⟶ 843:
 
=={{header|Genie}}==
<langsyntaxhighlight lang="genie">[indent=4]
/*
Execute system command, in Genie
Line 679 ⟶ 856:
Process.spawn_command_line_async("ls")
except e : SpawnError
stderr.printf("%s\n", e.message)</langsyntaxhighlight>
 
{{out}}
Line 690 ⟶ 867:
...
</pre>
 
=={{header|gnuplot}}==
 
<syntaxhighlight lang="gnuplot">!ls</syntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 707 ⟶ 888:
log.Fatal(err)
}
}</langsyntaxhighlight>
 
=={{header|gnuplot}}==
 
<lang gnuplot>!ls</lang>
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">println "ls -la".execute().text</langsyntaxhighlight>
 
=={{header|GUISS}}==
 
<langsyntaxhighlight lang="guiss">Start,Programs,Accessories,MSDOS Prompt,Type:dir[enter]</langsyntaxhighlight>
 
=={{header|Haskell}}==
{{works with|GHC|GHCi|6.6}}
<langsyntaxhighlight lang="haskell">import System.Cmd
 
main = system "ls"
</syntaxhighlight>
</lang>
 
See also: the [http://www.haskell.org/ghc/docs/latest/html/libraries/process-1.2.0.0/System-Process.html System.Process] module
 
=={{header|HicEst}}==
<langsyntaxhighlight lang="hicest">SYSTEM(CoMmand='pause')
SYSTEM(CoMmand='dir & pause') </langsyntaxhighlight>
 
=={{header|HolyC}}==
Line 738 ⟶ 915:
For example, to execute the <code>Dir</code> command:
 
<syntaxhighlight lang ="holyc">Dir;</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
The code below selects the 'ls' or 'dir' command at runtime based on the UNIX feature.
 
<langsyntaxhighlight Iconlang="icon">procedure main()
 
write("Trying command ",cmd := if &features == "UNIX" then "ls" else "dir")
system(cmd)
 
end</langsyntaxhighlight>
 
Unicon extends system to allow specification of files and a wait/nowait parameter as in the examples below.
<syntaxhighlight lang="icon">
<lang Icon>
pid := system(command_string,&input,&output,&errout,"wait")
pid := system(command_string,&input,&output,&errout,"nowait")
</syntaxhighlight>
</lang>
 
=={{header|IDL}}==
<syntaxhighlight lang ="idl">$ls</langsyntaxhighlight>
 
Will execute "ls" with output to the screen.
 
<langsyntaxhighlight lang="idl">spawn,"ls",result</langsyntaxhighlight>
 
will execute it and store the result in the string array "result".
 
<langsyntaxhighlight lang="idl">spawn,"ls",unit=unit</langsyntaxhighlight>
 
will execute it asynchronously and direct any output from it into the LUN "unit" from whence it can be read at any (later) time.
 
=={{header|Io}}==
<langsyntaxhighlight lang="io">System runCommand("ls") stdout println</langsyntaxhighlight>
 
=={{header|IS-BASIC}}==
<syntaxhighlight lang="is-basic">100 EXT "dir"</syntaxhighlight>
 
=={{header|J}}==
 
The system command interface in J is provided by the standard "task" script:
<langsyntaxhighlight lang="j">load'task'
 
NB. Execute a command and wait for it to complete
Line 788 ⟶ 969:
NB. and capture its stdout
stdin =: 'blahblahblah'
stdout =: stdin spawn 'grep blah'</langsyntaxhighlight>
 
Note that on unix systems, you can also use the [http://www.jsoftware.com/help/dictionary/dx002.htm 2!:x family] of foreign verbs to execute system commands.
Line 794 ⟶ 975:
=={{header|Java}}==
{{works with|Java|1.5+}}
<langsyntaxhighlight lang="java5">import java.util.Scanner;
import java.io.*;
 
Line 808 ⟶ 989:
}
}
}</langsyntaxhighlight>
 
{{works with|Java|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)
<langsyntaxhighlight lang="java">import java.io.IOException;
import java.io.InputStream;
 
Line 850 ⟶ 1,031:
}</langsyntaxhighlight>
 
And the right way, which uses threading to read the InputStream given by the process.
<langsyntaxhighlight lang="java">import java.io.IOException;
import java.io.InputStream;
 
Line 916 ⟶ 1,097:
}
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Line 922 ⟶ 1,103:
 
{{works with|JScript}}
<langsyntaxhighlight lang="javascript">var shell = new ActiveXObject("WScript.Shell");
shell.run("cmd /c dir & pause");</langsyntaxhighlight>
 
{{works with|Rhino}}
<langsyntaxhighlight lang="javascript">runCommand("cmd", "/c", "dir", "d:\\");
print("===");
var options = {
Line 935 ⟶ 1,116:
};
runCommand("cmd", options);
print(options.output);</langsyntaxhighlight>
 
=={{header|Joy}}==
<lang<syntaxhighlight lang="joy">"ls" system.</langsyntaxhighlight>
 
=={{header|Julia}}==
The Julia manual has an excellent [http://docs.julialang.org/en/release-0.3/manual/running-external-programs/ section] on this topic, which is worth a read. The short answer on Linux is:
<syntaxhighlight lang Julia="julia">run(`ls`)</langsyntaxhighlight>
 
{{out}}
Line 959 ⟶ 1,140:
 
Execute "ls"
<syntaxhighlight lang K="k"> \ls</langsyntaxhighlight>
 
Execute "ls" and capture the output in the variable "r":
<langsyntaxhighlight Klang="k"> r: 4:"ls"</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6
 
import java.util.Scanner
Line 974 ⟶ 1,155:
while (it.hasNextLine()) println(it.nextLine())
}
}</langsyntaxhighlight>
 
=={{header|Lang5}}==
For one-word commands:
<syntaxhighlight lang Lang5="lang5">'ls system</langsyntaxhighlight>
For multi-word commands:
<langsyntaxhighlight Lang5lang="lang5">"ls -a" system</langsyntaxhighlight>
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">local(
path = file_forceroot,
ls = sys_process('/bin/ls', (:'-l', #path)),
Line 990 ⟶ 1,171:
'<pre>'
#ls -> read
'</pre>'</langsyntaxhighlight>
<pre>total 16
drwxr-xr-x 8 _lasso staff 272 Nov 10 08:13 mydir
Line 1,000 ⟶ 1,181:
In the LFE REPL:
 
<langsyntaxhighlight lang="lisp">
> (os:cmd "ls -alrt")
</syntaxhighlight>
</lang>
 
That will display output on a single line, with literal newlines.
Line 1,008 ⟶ 1,189:
For pretty output, compose with <code>io:format</code>:
 
<langsyntaxhighlight lang="lisp">
> (io:format (os:cmd "ls -alrt"))
</syntaxhighlight>
</lang>
 
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
drive1$ = left$(Drives$,1)
run "cmd.exe /";drive1$;" dir & pause"
</langsyntaxhighlight>
 
=={{header|Lingo}}==
{{libheader|Shell Xtra}}
<lang lingo>sx = xtra("Shell").new()
if the platform contains "win" then
put sx.shell_cmd("dir")
else
put sx.shell_cmd("ls")
end if</lang>
 
=={{header|Limbo}}==
Line 1,034 ⟶ 1,205:
This version passes its argument list through to ls:
 
<langsyntaxhighlight Limbolang="limbo">implement Runls;
 
include "sys.m"; sys: Sys;
Line 1,057 ⟶ 1,228:
sys->fprint(sys->fildes(2), "runls: %s: %r", s);
raise "fail:errors";
}</langsyntaxhighlight>
 
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.
 
=={{header|Lingo}}==
{{libheader|Shell Xtra}}
<syntaxhighlight lang="lingo">sx = xtra("Shell").new()
if the platform contains "win" then
put sx.shell_cmd("dir")
else
put sx.shell_cmd("ls")
end if</syntaxhighlight>
 
=={{header|Locomotive Basic}}==
Line 1,065 ⟶ 1,245:
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):
 
<syntaxhighlight lang ="basic">LIST</langsyntaxhighlight>
 
=={{header|Logo}}==
{{works with|UCB Logo}}
The lines of output of the SHELL command are returned as a list.
<langsyntaxhighlight lang="logo">print first butfirst shell [ls -a] ; ..</langsyntaxhighlight>
 
=={{header|Logtalk}}==
Using the standard library:
<langsyntaxhighlight lang="logtalk">os::shell('ls -a').</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight 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</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
 
<syntaxhighlight lang="m2000 interpreter">
Locale 1033 // for the chr$(string) : converτ ANSI to UTF16LE
Dos "chdir "+quote$(dir$)+"&& dir /w > out.txt";
Wait 100
Print "Press Space or Mouse to see next page"
A$=chr$(eval$(buffer("out.txt")))
Report a$ // view text using proportional typing, and at pages, with 3/4height scroll
</syntaxhighlight>
 
 
 
=={{header|M4}}==
<langsyntaxhighlight M4lang="m4">syscmd(ifdef(`__windows__',`dir',`ls'))</langsyntaxhighlight>
 
=={{header|Make}}==
Line 1,092 ⟶ 1,285:
in definition
 
<langsyntaxhighlight lang="make">contents=$(shell cat foo)
curdir=`pwd`</langsyntaxhighlight>
 
in target
 
<langsyntaxhighlight lang="make">mytarget:
cat foo | grep mytext</langsyntaxhighlight>
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">ssystem("dir");</langsyntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">Run["ls"]</langsyntaxhighlight>
 
=={{header|MATLAB}}==
Line 1,110 ⟶ 1,303:
 
Sample Usage:
<langsyntaxhighlight MATLABlang="matlab">>> system('PAUSE')
 
Press any key to continue . . .
Line 1,118 ⟶ 1,311:
 
0
</syntaxhighlight>
</lang>
 
=={{header|Maxima}}==
<syntaxhighlight lang="text">system("dir > list.txt")$</langsyntaxhighlight>
 
=={{header|MAXScript}}==
<langsyntaxhighlight lang="maxscript">dosCommand "pause"</langsyntaxhighlight>
 
=={{header|Mercury}}==
<syntaxhighlight lang="text">
:- module execute_sys_cmd.
:- interface.
Line 1,138 ⟶ 1,331:
main(!IO) :-
io.call_system("ls", _Result, !IO).
</syntaxhighlight>
</lang>
 
=={{header|min}}==
{{works with|min|0.19.3}}
<syntaxhighlight lang ="min">!dir</langsyntaxhighlight>
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE tri;
 
FROM SYSTEM IMPORT ADR;
Line 1,178 ⟶ 1,371:
InOut.WriteLn;
InOut.WriteBf
END tri.</langsyntaxhighlight>
 
=={{header|Modula-3}}==
Line 1,184 ⟶ 1,377:
 
Also note the <code>EVAL</code> keyword, which ignores the return value of a function.
<langsyntaxhighlight lang="modula3">UNSAFE MODULE Exec EXPORTS Main;
 
IMPORT Unix, M3toC;
Line 1,193 ⟶ 1,386:
EVAL Unix.system(command);
M3toC.FreeCopiedS(command);
END Exec.</langsyntaxhighlight>
 
=={{header|MUMPS}}==
<p>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.</p>
<p>In Caché on OpenVMS in an FILES-11 filesystem ODS-5 mode this could work:
<langsyntaxhighlight MUMPSlang="mumps">Set X=$ZF(-1,"DIR")</langsyntaxhighlight></p>
 
<p>In GT.M on OpenVMS, the following will work:
<langsyntaxhighlight MUMPSlang="mumps">ZSY "DIR"</langsyntaxhighlight></p>
<p>GT.M on UNIX is the same:
<langsyntaxhighlight MUMPSlang="mumps">ZSY "ls"</langsyntaxhighlight></p>
<p>Note: $ZF in GT.M is Unicode version of $F[ind].</p>
 
=={{header|Nanoquery}}==
<syntaxhighlight lang="nanoquery">shell("ls")</syntaxhighlight>
 
=={{header|NetRexx}}==
{{Trans|Java}}
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols binary
 
Line 1,215 ⟶ 1,412:
return
 
-- 10:43, 27 August 2022 (UTC)10:43, 27 August 2022 (UTC)10:43, 27 August 2022 (UTC)10:43, 27 August 2022 (UTC)10:43, 27 August 2022 (UTC)10:43, 27 August 2022 (UTC)10:43, 27 August 2022 (UTC)10:43, 27 August 2022 (UTC)10:43, 27 August 2022 (UTC)10:43, 27 August 2022 (UTC)10:43, 27 August 2022 (UTC)10:43, 27 August 2022 (UTC)10:43, 27 August 2022 (UTC)10:43, 27 August 2022 (UTC)10:43, 27 August 2022 (UTC)~~
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) private static
parse arg command
Line 1,230 ⟶ 1,427:
end
return
</syntaxhighlight>
</lang>
 
=={{header|NewLISP}}==
<langsyntaxhighlight NewLISPlang="newlisp">(exec "ls")</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import osproc
 
let exitCode = execCmd "ls"
let (output, exitCode2) = execCmdEx "ls"</langsyntaxhighlight>
 
=={{header|Objective-C}}==
{{works with|GCC}}<br>
NSTask runs an external process with explicit path and arguments.
<langsyntaxhighlight lang="objc">void runls()
{
[[NSTask launchedTaskWithLaunchPath:@"/bin/ls"
arguments:@[]] waitUntilExit];
}</langsyntaxhighlight>
If you need to run a system command, invoke the shell:
<langsyntaxhighlight lang="objc">void runSystemCommand(NSString *cmd)
{
[[NSTask launchedTaskWithLaunchPath:@"/bin/sh"
arguments:@[@"-c", cmd]]
waitUntilExit];
}</langsyntaxhighlight>
Complete usage example:
 
Line 1,261 ⟶ 1,458:
{{works with|Cocoa}}<br>
{{works with|GNUstep}}
<langsyntaxhighlight lang="objc">#import <Foundation/Foundation.h>
 
void runSystemCommand(NSString *cmd)
Line 1,277 ⟶ 1,474:
}
return 0;
}</langsyntaxhighlight>
Or use the C method above.
 
Line 1,283 ⟶ 1,480:
Just run the command:
 
<langsyntaxhighlight lang="ocaml">Sys.command "ls"</langsyntaxhighlight>
 
To capture the output of the command:
 
<langsyntaxhighlight lang="ocaml">#load "unix.cma"
 
let syscall cmd =
Line 1,300 ⟶ 1,497:
(Buffer.contents buf)
 
let listing = syscall "ls" ;;</langsyntaxhighlight>
 
 
a more complete version which also returns the contents from stderr, and checks the exit-status, and where the environment can be specified:
 
<langsyntaxhighlight 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
Line 1,325 ⟶ 1,522:
check_exit_status exit_status;
(Buffer.contents buf1,
Buffer.contents buf2)</langsyntaxhighlight>
 
val syscall : ?env:string array -> string -> string * string
 
=={{header|Octave}}==
<langsyntaxhighlight lang="octave">system("ls");</langsyntaxhighlight>
 
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">System cmd("pause")</langsyntaxhighlight>
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">{OS.system "ls" _}</langsyntaxhighlight>
 
A more sophisticated example can be found [http://www.mozart-oz.org/home/doc/op/node17.html here].
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">system("ls")</langsyntaxhighlight>
 
=={{header|Pascal}}==
{{works with|Free_Pascal}} {{libheader|SysUtils}}
<langsyntaxhighlight lang="pascal">Program ExecuteSystemCommand;
 
uses
Line 1,352 ⟶ 1,549:
begin
ExecuteProcess('/bin/ls', '-alh');
end.</langsyntaxhighlight>
 
=={{header|Perl}}==
<lang perl>my @results = qx(ls); # run command and return STDOUT as a string
 
my @results = `ls`; # same, alternative syntax
 
system "ls"; # run command and return exit status; STDOUT of command goes program STDOUT
 
print `ls`; # same, but with back quotes
 
exec "ls"; # replace current process with another</lang>
 
See also:
http://perldoc.perl.org/perlipc.html#Using-open()-for-IPC
http://perldoc.perl.org/IPC/Open3.html
 
=={{header|Perl 6}}==
<lang perl6>run "ls" orelse .die; # output to stdout
 
my @ls = qx/ls/; # output to variable
 
my $cmd = 'ls';
@ls = qqx/$cmd/; # same thing with interpolation</lang>
 
=={{header|PDP-11 Assembly}}==
PDP-11 running Unix
<langsyntaxhighlight lang="pdp-11">; Execute a file - the equivalent of system() in stdio
;
; On entry, r1=>nul-terminated command string
Line 1,436 ⟶ 1,610:
EQUW 0
EQUW 0
EQUW 0</langsyntaxhighlight>
So, call with, for example:
<langsyntaxhighlight lang="pdp-11">mov #cmd_ls,r1 ; => "ls" command string
jsr pc,CLIsystem
...
.cmd_ls EQUS "ls",0</langsyntaxhighlight>
 
=={{header|Perl}}==
<syntaxhighlight lang="perl">my @results = qx(ls); # run command and return STDOUT as a string
 
my @results = `ls`; # same, alternative syntax
 
system "ls"; # run command and return exit status; STDOUT of command goes program STDOUT
 
print `ls`; # same, but with back quotes
 
exec "ls"; # replace current process with another</syntaxhighlight>
 
See also:
http://perldoc.perl.org/perlipc.html#Using-open()-for-IPC
http://perldoc.perl.org/IPC/Open3.html
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(notonline)-->
<lang Phix>string cmd = iff(platform()=WINDOWS?"dir":"ls")
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span>
system(cmd)
<span style="color: #004080;">string</span> <span style="color: #000000;">cmd</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()=</span><span style="color: #004600;">WINDOWS</span><span style="color: #0000FF;">?</span><span style="color: #008000;">"dir"</span><span style="color: #0000FF;">:</span><span style="color: #008000;">"ls"</span><span style="color: #0000FF;">)</span>
integer res = system_exec("pause",4)</lang>
<span style="color: #7060A8;">system</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cmd</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">system_exec</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"pause"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
system_exec allows you to specify whether you want a command shell or not, and whether to wait for a result. In the case of pause, the 4 signifies that we need a shell and we want to wait for it to complete.
 
=={{header|PHP}}==
The first line execute the command and the second line display the output:
<langsyntaxhighlight lang="php">@exec($command,$output);
echo nl2br($output);</langsyntaxhighlight>
'''Note:'''The '@' is here to prevent error messages to be displayed, 'nl2br' translate '\n' chars to 'br' in HTML.
 
Other:
<langsyntaxhighlight lang="php">$results = `ls`;
# runs command and returns its STDOUT as a string
 
Line 1,466 ⟶ 1,658:
 
passthru("ls");
# like system() but binary-safe</langsyntaxhighlight>
 
See also: [http://us.php.net/manual/en/function.proc-open.php proc_open()]
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(call "ls")</langsyntaxhighlight>
 
=={{header|Pike}}==
<langsyntaxhighlight 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");
Line 1,485 ⟶ 1,677:
Process.create_process(({"ls", "-l"}), ([ "stdout" : stdout->pipe() ]) );
write(stdout->read() + "\n");
}</langsyntaxhighlight>
 
=={{header|Plain English}}==
<syntaxhighlight lang="text">
A command is a string.
A parameter is a string.
 
To run:
Start up.
Execute "dir" on the command line.
Shut down.
 
To execute a command on the command line:
Put "/c " then the command into a parameter.
Null terminate the parameter.
Put "cmd" into a string.
Null terminate the string.
Call "shell32.dll" "ShellExecuteA" with nil and nil and the string's first and the parameter's first and nil and 1.
</syntaxhighlight>
 
=={{header|Pop11}}==
The sysobey function runs commands using a shell:
 
<syntaxhighlight lang ="pop11">sysobey('ls');</langsyntaxhighlight>
 
=={{header|PowerShell}}==
Since PowerShell is a shell, running commands is the default operation.
<langsyntaxhighlight lang="powershell">dir
ls
Get-ChildItem</langsyntaxhighlight>
are all equivalent (the first two are aliases for the third) but they are PowerShell-native commands. If one really needs to execute <code>dir</code> (which is no program but rather a built-in command in <code>cmd.exe</code>) this can be achieved by
<syntaxhighlight lang ="powershell">cmd /c dir</langsyntaxhighlight>
 
=={{header|Prolog}}==
Line 1,504 ⟶ 1,714:
 
{{works with|GNU Prolog}}
<syntaxhighlight lang ="prolog">shell('ls').</langsyntaxhighlight>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">ImportC "msvcrt.lib"
system(str.p-ascii)
EndImport
Line 1,516 ⟶ 1,727:
Input()
CloseConsole()
EndIf</langsyntaxhighlight>
 
=={{header|Python}}==
<langsyntaxhighlight 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.</langsyntaxhighlight>
or
 
{{works with|Python|2.7 (and above)}}
<langsyntaxhighlight 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+</langsyntaxhighlight>
 
or
 
{{works with|Python|2.4 (and above)}}
<langsyntaxhighlight lang="python">from subprocess import PIPE, Popen, STDOUT
p = Popen('ls', stdout=PIPE, stderr=STDOUT)
print p.communicate()[0]</langsyntaxhighlight>
 
'''Note:''' The latter is the preferred method for calling external processes, although cumbersome, it gives you finer control over the process.
Line 1,543 ⟶ 1,754:
 
{{works with|Python|2.2 (and above)}}
<langsyntaxhighlight lang="python">import commands
stat, out = commands.getstatusoutput('ls')
if not stat:
print out</langsyntaxhighlight>
 
=={{header|Quackery}}==
 
{{trans|Python}}
 
<syntaxhighlight lang="quackery">$ \
import os
exit_code = os.system('ls')
\ python</syntaxhighlight>
 
{{out}}
 
<pre>Quackery Quick Reference.pdf extensionsX.qky
READ ME FIRST.txt quackery.py
The Book of Quackery for print.pdf sundry
The Book of Quackery.pdf turtleduck.qky
bigrat.qky</pre>
 
=={{header|R}}==
<langsyntaxhighlight Rlang="r">system("ls")
output=system("ls",intern=TRUE)</langsyntaxhighlight>
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 1,568 ⟶ 1,796:
;; avoid specifying the executable path
(system* (find-executable-path "/bin/ls") "-l")
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>run "ls" orelse .die; # output to stdout
 
my @ls = qx/ls/; # output to variable
 
my $cmd = 'ls';
@ls = qqx/$cmd/; # same thing with interpolation</syntaxhighlight>
 
=={{header|Raven}}==
Back tick string is auto executed:
 
<syntaxhighlight lang ="raven">`ls -la` as listing</langsyntaxhighlight>
 
Or specifically on any string:
 
<langsyntaxhighlight lang="raven">'ls -la' shell as listing</langsyntaxhighlight>
 
=={{header|REBOL}}==
<langsyntaxhighlight REBOLlang="rebol">; Capture output to string variable:
 
x: "" call/output "dir" x
Line 1,594 ⟶ 1,831:
; The 'shell' refinement may be necessary to launch some programs.
 
call/shell "notepad.exe"</langsyntaxhighlight>
 
=={{header|Red}}==
<langsyntaxhighlight lang="red">
call/show %pause ;The /show refinement forces the display of system's shell window (Windows only).
call/show %dir
call/show %notepad.exe</langsyntaxhighlight>
 
=={{header|REXX}}==
Since REXX is a shell scripting language, it's easy to execute commands:
<langsyntaxhighlight REXXlang="rexx">"dir /a:d"</langsyntaxhighlight>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
system("dir")
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">string = `ls`
# runs command and returns its STDOUT as a string
string = %x{ls}
Line 1,629 ⟶ 1,866:
io = IO.popen('ls')
# ... later
io.each {|line| puts line}</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">print shell$("ls") ' prints the returned data from the OS
a$ = shell$("ls") ' holds returned data in a$</langsyntaxhighlight>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">use std::process::Command;
fn main() {
let output = Command::new("ls").output().unwrap_or_else(|e| {
Line 1,643 ⟶ 1,880:
println!("{}", String::from_utf8_lossy(&output.stdout));
}
</syntaxhighlight>
</lang>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">import scala.sys.process.Process
Process("ls", Seq("-oa"))!</langsyntaxhighlight>
 
=={{header|Scheme}}==
{{works with|Guile}}
{{works with|Chicken Scheme}}
<langsyntaxhighlight lang="scheme">(system "ls")</langsyntaxhighlight>
 
=={{header|Seed7}}==
Line 1,664 ⟶ 1,901:
Anyway, the task was to use a system command, so here is the example:
 
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "shell.s7i";
 
Line 1,670 ⟶ 1,907:
begin
cmd_sh("ls");
end func;</langsyntaxhighlight>
 
=={{header|SETL}}==
<langsyntaxhighlight SETLlang="setl">system("ls");</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby"># Pipe in read-only mode
%p(ls).open_r.each { |line|
print line;
Line 1,685 ⟶ 1,922:
 
Sys.system('ls'); # system: executes a command and prints the result
Sys.exec('ls'); # replaces current process with another</langsyntaxhighlight>
 
=={{header|Slate}}==
Line 1,691 ⟶ 1,928:
Run a command normally through the shell:
<syntaxhighlight lang ="slate">Platform run: 'ls'.</langsyntaxhighlight>
 
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):
 
<langsyntaxhighlight lang="slate">shell ls: '*.slate'.</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
 
<syntaxhighlight lang ="smalltalk">Smalltalk system: 'ls'.</langsyntaxhighlight>
 
=={{header|Standard ML}}==
Just run the command:
 
<lang sml>OS.Process.system "ls"</lang>
 
=={{header|SQL PL}}==
{{works with|Db2 LUW}}
In Linux or UNIX:
<langsyntaxhighlight lang="sql pl">
!ls
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,727 ⟶ 1,959:
</pre>
In Windows:
<langsyntaxhighlight lang="sql pl">
!dir
</syntaxhighlight>
</lang>
 
=={{header|Standard ML}}==
Just run the command:
 
<syntaxhighlight lang="sml">OS.Process.system "ls"</syntaxhighlight>
 
=={{header|Stata}}==
Line 1,736 ⟶ 1,973:
The command '''!''' (or equivalently '''shell'''), opens a Windows console to run the command, while '''winexec''' does not.
 
<langsyntaxhighlight lang="stata">!dir
 
* print a message and wait
Line 1,748 ⟶ 1,985:
 
* load Windows Notepad
winexec notepad</langsyntaxhighlight>
 
=={{header|Tcl}}==
 
<syntaxhighlight lang ="tcl">puts [exec ls]</langsyntaxhighlight>
 
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.
Line 1,758 ⟶ 1,995:
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:
 
<langsyntaxhighlight lang="tcl">set io [open "|ls" r]</langsyntaxhighlight>
 
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:
 
<syntaxhighlight lang ="tcl">set nextline [gets $io]</langsyntaxhighlight>
or read the whole shebang in a fell swoop:
 
<syntaxhighlight lang ="tcl">set lsoutput [read $io]</langsyntaxhighlight>
 
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.
 
<syntaxhighlight lang="tcl">exec C:/Windows/System32/taskmgr.exe &</syntaxhighlight>
 
Runs the Task Manager on Windows. If running from a Tcl/Tk Gui the [ & ] prevents blocking the Gui.
 
=={{header|Toka}}==
<langsyntaxhighlight lang="toka">needs shell
" ls" system</langsyntaxhighlight>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
system=SYSTEM ()
Line 1,783 ⟶ 2,024:
EXECUTE "ls -l"
ENDIF
</syntaxhighlight>
</lang>
 
=={{header|UNIX Shell}}==
UNIX shells are designed to run system commands as a default operation.
<syntaxhighlight lang ="bash">ls</langsyntaxhighlight>
 
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.
 
<syntaxhighlight lang ="bash">exec ls</langsyntaxhighlight>
 
===Command substitution===
Line 1,797 ⟶ 2,038:
 
With [[Bourne Shell]]:
<langsyntaxhighlight lang="bash">output=`ls`</langsyntaxhighlight>
 
With [[Korn Shell]] or any modern shell:
<langsyntaxhighlight lang="bash">output=$(ls)</langsyntaxhighlight>
 
* '''Note 1:''' in <code>`ls`</code>, these are "backticks" rather than quotes or apostrophes.
Line 1,808 ⟶ 2,049:
The '''`...`''' form is difficult to nest, but the '''$(...)''' form is very nestable.
 
<langsyntaxhighlight lang="bash">output=`expr \`echo hi | wc -c\` - 1`
output=$(expr $(echo hi | wc -c) - 1)</langsyntaxhighlight>
 
Both forms, `backticks` and '''$(...)''', also work inside double-quoted strings. This prevents file name expansion and also prevents word splitting.
 
<langsyntaxhighlight lang="bash">echo "Found: `grep 80/tcp /etc/services`"
echo "Found: $(grep 80/tcp /etc/services)"</langsyntaxhighlight>
 
==={{header|C Shell}}===
C Shell also runs system commands, and has an '''exec''' built-in command, exactly like Bourne Shell.
 
<langsyntaxhighlight lang="csh">ls # run command, return to shell
exec ls # replace shell with command</langsyntaxhighlight>
 
`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.
 
<langsyntaxhighlight lang="csh">set output=( "`grep 80/ /etc/services`" )
echo "Line 1: $output[1]"
echo "Line 2: $output[2]"</langsyntaxhighlight>
 
=={{header|Ursa}}==
<langsyntaxhighlight lang="ursa">decl string<> arg
decl string<> output
decl iodevice iod
Line 1,839 ⟶ 2,080:
for (decl int i) (< i (size output)) (inc i)
out output<i> endl console
end for</langsyntaxhighlight>
 
=={{header|Ursala}}==
Line 1,851 ⟶ 2,092:
Here is a self-contained command line application providing a limited replacement
for the ls command.
<langsyntaxhighlight Ursalalang="ursala">#import std
#import cli
 
#executable ('parameterized','')
 
myls = <.file$[contents: --<''>]>@hm+ (ask bash)/0+ -[ls --color=no]-!</langsyntaxhighlight>
The color option is needed to suppress terminal escape sequences.
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
Set objShell = CreateObject("WScript.Shell")
objShell.Run "%comspec% /K dir",3,True
</syntaxhighlight>
</lang>
 
=={{header|Vedit macro language}}==
 
<langsyntaxhighlight lang="vedit">system("dir", DOS)</langsyntaxhighlight>
 
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:
 
<langsyntaxhighlight lang="vedit">system('cmd /k "dir"')</langsyntaxhighlight>
 
=={{header|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.
<langsyntaxhighlight lang="vb">Attribute VB_Name = "mdlShellAndWait"
Option Explicit
 
Line 1,952 ⟶ 2,193:
Sub SpawnDir()
ShellAndWait("dir", 10)
End Sub</langsyntaxhighlight>
 
=={{header|Visual Basic .NET}}==
{{works with|Visual Basic .NET|9.0+}}
<langsyntaxhighlight lang="vbnet">Module System_Command
 
Sub Main()
Line 1,976 ⟶ 2,217:
 
End Module
</syntaxhighlight>
</lang>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">
import os
 
fn main() {
result := os.execute('cmd /c dir')
if result.output !='' {println(result.output)}
else {println('Error: not working') exit(1)}
}
</syntaxhighlight>
 
=={{header|Wart}}==
<langsyntaxhighlight lang="wart">system "ls"</langsyntaxhighlight>
 
=={{header|Wren}}==
Wren CLI doesn't currently expose a way to execute a system command.
 
However, if Wren is embedded in (say) a suitable Go program, then we can ask the latter to do it for us.
 
<syntaxhighlight lang="wren">/* Execute_a_system_command.wren */
class Command {
foreign static exec(name, param) // the code for this is provided by Go
}
 
Command.exec("ls", "-lt")
System.print()
Command.exec("dir", "")</syntaxhighlight>
 
which we embed in the following Go program and run it.
{{libheader|WrenGo}}
<syntaxhighlight lang="go">/* Execute_a_system_command.go*/
package main
 
import (
wren "github.com/crazyinfin8/WrenGo"
"log"
"os"
"os/exec"
)
 
type any = interface{}
 
func execCommand(vm *wren.VM, parameters []any) (any, error) {
name := parameters[1].(string)
param := parameters[2].(string)
var cmd *exec.Cmd
if param != "" {
cmd = exec.Command(name, param)
} else {
cmd = exec.Command(name)
}
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
log.Fatal(err)
}
return nil, nil
}
 
func main() {
vm := wren.NewVM()
fileName := "Execute_a_system_command.wren"
methodMap := wren.MethodMap{"static exec(_,_)": execCommand}
classMap := wren.ClassMap{"Command": wren.NewClass(nil, nil, methodMap)}
module := wren.NewModule(classMap)
vm.SetModule(fileName, module)
vm.InterpretFile(fileName)
vm.Free()
}</syntaxhighlight>
 
=={{header|x86 Assembly}}==
{{works with|NASM}}
{{works with|Linux}}
32 bit
<syntaxhighlight lang="asm">
; Executes '/bin/ls'
; Build with:
; nasm -felf32 execls.asm
; ld -m elf_i386 execls.o -o execls
 
global _start
section .text
 
_start:
mov eax, 0x0B ; sys_execve(char *str, char **args, char **envp)
mov ebx, .path ; pathname
push DWORD 0
push DWORD .path
lea ecx, [esp] ; arguments [pathname]
xor edx, edx ; environment variables []
int 0x80 ; syscall
.path:
db '/bin/ls', 0x00
</syntaxhighlight>
 
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">system("dir")
//It will return the exit code of the command; its output (if any) will be lost.
 
 
print system$("dir")
//Returns the output as a large string.</syntaxhighlight>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">System.cmd(System.isWindows and "dir" or "ls")</langsyntaxhighlight>
 
=={{header|ZX Spectrum Basic}}==
Line 1,987 ⟶ 2,329:
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:
 
<syntaxhighlight lang ="zxbasic">PAUSE 100</langsyntaxhighlight>
 
{{omit from|EasyLang}}
{{omit from|Retro}}
{{omit from|TI-83 BASIC}} {{omit from|TI-89 BASIC}} <!-- Does not have an external OS/command processor. -->
9,476

edits