Execute a system command: Difference between revisions

From Rosetta Code
Content added Content deleted
m (→‎{{header|Phix}}: added syntax colouring, marked p2js incompatible)
m (→‎{{header|Wren}}: Minor tidy)
 
(21 intermediate revisions by 11 users not shown)
Line 9: Line 9:


=={{header|11l}}==
=={{header|11l}}==
<lang 11l>os:(‘pause’)</lang>
<syntaxhighlight lang="11l">os:(‘pause’)</syntaxhighlight>


=={{header|ABAP}}==
=={{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.
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.


<lang abap>*&---------------------------------------------------------------------*
<syntaxhighlight lang="abap">*&---------------------------------------------------------------------*
*& Report ZEXEC_SYS_CMD
*& Report ZEXEC_SYS_CMD
*&
*&
Line 147: Line 147:
ENDIF.
ENDIF.
ENDIF.
ENDIF.
ENDIF.</lang>
ENDIF.</syntaxhighlight>


=={{header|Ada}}==
=={{header|Ada}}==
Using the IEEE POSIX Ada standard, P1003.5c:
Using the IEEE POSIX Ada standard, P1003.5c:
<lang ada>with POSIX.Unsafe_Process_Primitives;
<syntaxhighlight lang="ada">with POSIX.Unsafe_Process_Primitives;


procedure Execute_A_System_Command is
procedure Execute_A_System_Command is
Line 158: Line 158:
POSIX.Append (Arguments, "ls");
POSIX.Append (Arguments, "ls");
POSIX.Unsafe_Process_Primitives.Exec_Search ("ls", Arguments);
POSIX.Unsafe_Process_Primitives.Exec_Search ("ls", Arguments);
end Execute_A_System_Command;</lang>
end Execute_A_System_Command;</syntaxhighlight>


Importing the C system() function:
Importing the C system() function:
<lang ada>with Interfaces.C; use Interfaces.C;
<syntaxhighlight lang="ada">with Interfaces.C; use Interfaces.C;


procedure Execute_System is
procedure Execute_System is
Line 169: Line 169:
begin
begin
Ret_Val := Sys(To_C("ls"));
Ret_Val := Sys(To_C("ls"));
end Execute_System;</lang>
end Execute_System;</syntaxhighlight>


Using the GNAT run-time library:
Using the GNAT run-time library:
<lang ada>
<syntaxhighlight lang="ada">
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Text_IO; use Ada.Text_IO;
with System.OS_Lib; use System.OS_Lib;
with System.OS_Lib; use System.OS_Lib;
Line 193: Line 193:
end loop;
end loop;
end Execute_Synchronously;
end Execute_Synchronously;
</syntaxhighlight>
</lang>


=={{header|Aikido}}==
=={{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).
The simplest way to do this is using the <code>system()</code> function. It returns a vector of strings (the output from the command).
<lang aikido>
<syntaxhighlight lang="aikido">
var lines = system ("ls")
var lines = system ("ls")
foreach line lines {
foreach line lines {
println (line)
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;
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;
<lang aikido>
<syntaxhighlight lang="aikido">
exec ("ls")
exec ("ls")
</syntaxhighlight>
</lang>
You also have the regular <code>fork</code> and <code>execv</code> calls available:
You also have the regular <code>fork</code> and <code>execv</code> calls available:
<lang aikido>
<syntaxhighlight lang="aikido">
var pid = fork()
var pid = fork()
if (pid == 0) {
if (pid == 0) {
Line 218: Line 218:
waitpid (pid, status)
waitpid (pid, status)


</syntaxhighlight>
</lang>


=={{header|Aime}}==
=={{header|Aime}}==
<lang aime>sshell ss;
<syntaxhighlight lang="aime">sshell ss;


ss.argv.insert("ls");
ss.argv.insert("ls");


o_(ss.link);
o_(ss.link);
</syntaxhighlight>
</lang>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9 - "system" is not part of the standard's prelude.}}
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9 - "system" is not part of the standard's prelude.}}
<lang algol68>system("ls")</lang>
<syntaxhighlight lang="algol68">system("ls")</syntaxhighlight>


Or the classic "!" shell escape can be implemented as an "!" operator:
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.}}
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9 - "system" & "ANDF" are not part of the standard's prelude.}}
<lang algol68>OP ! = (STRING cmd)BOOL: system(cmd) = 0;
<syntaxhighlight lang="algol68">OP ! = (STRING cmd)BOOL: system(cmd) = 0;


IF ! "touch test.tmp" ANDF ( ! "ls test.tmp" ANDF ! "rm test.tmp" ) THEN
IF ! "touch test.tmp" ANDF ( ! "ls test.tmp" ANDF ! "rm test.tmp" ) THEN
print (("test.tmp now gone!", new line))
print (("test.tmp now gone!", new line))
FI</lang>
FI</syntaxhighlight>




=={{header|Amazing Hopper}}==
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="amazing hopper">
<lang Amazing Hopper>
#!/usr/bin/hopper
#!/usr/bin/hopper


Line 270: Line 270:


{0}return
{0}return
</syntaxhighlight>
</lang>


=={{header|APL}}==
=={{header|APL}}==
<syntaxhighlight lang="apl">
<lang APL>
∇ system s;handle
h ← ⎕fio['fork_daemon'] '/bin/ls /var'
⍝⍝ 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
backups games lib lock mail run tmp
cache gemini local log opt spool
cache gemini local log opt spool
</syntaxhighlight>
⎕fio['fclose'] h
0
</lang>


=={{header|AppleScript}}==
=={{header|AppleScript}}==
<lang applescript>do shell script "ls" without altering line endings</lang>
<syntaxhighlight lang="applescript">do shell script "ls" without altering line endings</syntaxhighlight>


=={{header|Applesoft BASIC}}==
=={{header|Applesoft BASIC}}==
<lang ApplesoftBASIC>? CHR$(4)"CATALOG"</lang>
<syntaxhighlight lang="applesoftbasic">? CHR$(4)"CATALOG"</syntaxhighlight>


=={{header|Arturo}}==
=={{header|Arturo}}==
<lang rebol>print execute "ls"</lang>
<syntaxhighlight lang="rebol">print execute "ls"</syntaxhighlight>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang autohotkey>Run, %comspec% /k dir & pause</lang>
<syntaxhighlight lang="autohotkey">Run, %comspec% /k dir & pause</syntaxhighlight>


=={{header|AutoIt}}==
=={{header|AutoIt}}==
<lang AutoIt>Run(@ComSpec & " /c " & 'pause', "", @SW_HIDE)</lang>
<syntaxhighlight lang="autoit">Run(@ComSpec & " /c " & 'pause', "", @SW_HIDE)</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==


Using system() function:
Using system() function:
<lang awk>BEGIN {
<syntaxhighlight lang="awk">BEGIN {
system("ls") # Unix
system("ls") # Unix
#system("dir") # DOS/MS-Windows
#system("dir") # DOS/MS-Windows
}</lang>
}</syntaxhighlight>


Using getline command:
Using getline command:
<lang awk>BEGIN {
<syntaxhighlight lang="awk">BEGIN {
ls = sys2var("ls")
ls = sys2var("ls")
print ls
print ls
Line 319: Line 325:
close(command)
close(command)
return ship
return ship
}</lang>
}</syntaxhighlight>


=={{header|BASIC}}==
=={{header|BASIC}}==


<lang qbasic>SHELL "dir"</lang>
<syntaxhighlight lang="qbasic">SHELL "dir"</syntaxhighlight>


==={{header|BaCon}}===
==={{header|BaCon}}===
<lang freebasic>' Execute a system command
<syntaxhighlight lang="freebasic">' Execute a system command
SYSTEM "ls"</lang>
SYSTEM "ls"</syntaxhighlight>

=={{header|BASIC256}}==
<syntaxhighlight lang="basic256">system "dir"</syntaxhighlight>


=={{header|Batch File}}==
=={{header|Batch File}}==


<lang batch>dir</lang>
<syntaxhighlight lang="batch">dir</syntaxhighlight>


=={{header|BBC BASIC}}==
=={{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.
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>
<syntaxhighlight lang="bbcbasic">OSCLI "CAT"</syntaxhighlight>


With BBC BASIC for Windows you can execute the Windows dir command:
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>
<syntaxhighlight lang="bbcbasic">OSCLI "*dir":REM *dir to bypass BB4W's built-in dir command</syntaxhighlight>


And if running BBC BASIC on a Unix host, you can execute the ls command:
And if running BBC BASIC on a Unix host, you can execute the ls command:
<lang bbcbasic>OSCLI "ls"</lang>
<syntaxhighlight lang="bbcbasic">OSCLI "ls"</syntaxhighlight>


=={{header|Befunge}}==
=={{header|Befunge}}==
{{works with|Befunge|98}}
{{works with|Befunge|98}}
Works with any Funge-98 on Unix, try https://tio.run/##S0pNK81LT9W1tNAtqAQz//9XKs5RsnX4/x8A
Works with any Funge-98 on Unix, try https://tio.run/##S0pNK81LT9W1tNAtqAQz//9XKs5RsnX4/x8A
<lang befunge>"sl"=@;pushes ls, = executes it, @ ends it;</lang>
<syntaxhighlight lang="befunge">"sl"=@;pushes ls, = executes it, @ ends it;</syntaxhighlight>




Line 354: Line 363:


The arguments to <code>•SH</code> are the command, followed by its arguments as a flat list of strings. For example:
The arguments to <code>•SH</code> are the command, followed by its arguments as a flat list of strings. For example:
<lang bqn>•SH ⟨"ls"⟩</lang>
<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.
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}}==
=={{header|Bracmat}}==
<lang bracmat>sys$dir</lang>
<syntaxhighlight lang="bracmat">sys$dir</syntaxhighlight>


=={{header|Brat}}==
=={{header|Brat}}==
<lang brat>include :subprocess
<syntaxhighlight lang="brat">include :subprocess


p subprocess.run :ls #Lists files in directory</lang>
p subprocess.run :ls #Lists files in directory</syntaxhighlight>


=={{header|Brlcad}}==
=={{header|Brlcad}}==


<lang brlcad>
<syntaxhighlight lang="brlcad">
exec ls
exec ls
</syntaxhighlight>
</lang>


=={{header|C}}==
=={{header|C}}==
ISO C & POSIX:
ISO C & POSIX:


<lang c>#include <stdlib.h>
<syntaxhighlight lang="c">#include <stdlib.h>


int main()
int main()
Line 381: Line 390:
system("ls");
system("ls");
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
Using Windows / .NET:
Using Windows / .NET:
<lang csharp>using System.Diagnostics;
<syntaxhighlight lang="csharp">using System.Diagnostics;


namespace Execute
namespace Execute
Line 396: Line 405:
}
}
}
}
}</lang>
}</syntaxhighlight>


{{works with|MCS|1.2.3.1}}
{{works with|MCS|1.2.3.1}}
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
class Execute {
class Execute {
Line 408: Line 417:
proc.Start();
proc.Start();
}
}
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
{{works with|Visual C++|2005}}
{{works with|Visual C++|2005}}
<lang cpp>system("pause");</lang>
<syntaxhighlight lang="cpp">system("pause");</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==


<lang lisp>(.. Runtime getRuntime (exec "cmd /C dir"))</lang>
<syntaxhighlight lang="lisp">(.. Runtime getRuntime (exec "cmd /C dir"))</syntaxhighlight>
<lang lisp>
<syntaxhighlight lang="lisp">


user=> (use '[clojure.java.shell :only [sh]])
user=> (use '[clojure.java.shell :only [sh]])
Line 437: Line 446:
drwxr-xr-x 4 zkim staff 136 Jul 5 13:15 src
drwxr-xr-x 4 zkim staff 136 Jul 5 13:15 src
, :err }
, :err }
</syntaxhighlight>
</lang>


<lang lisp>
<syntaxhighlight lang="lisp">
user=> (use '[clojure.java.shell :only [sh]])
user=> (use '[clojure.java.shell :only [sh]])


Line 454: Line 463:


nil
nil
</syntaxhighlight>
</lang>


=={{header|CMake}}==
=={{header|CMake}}==
{{works with|Unix}}
{{works with|Unix}}
<lang cmake>execute_process(COMMAND ls)</lang>
<syntaxhighlight lang="cmake">execute_process(COMMAND ls)</syntaxhighlight>


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.
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 464: Line 473:
''execute_process()'' can also chain commands in a pipeeline, and capture output.
''execute_process()'' can also chain commands in a pipeeline, and capture output.


<lang cmake># Calculate pi to 40 digits after the decimal point.
<syntaxhighlight lang="cmake"># Calculate pi to 40 digits after the decimal point.
execute_process(
execute_process(
COMMAND printf "scale = 45; 4 * a(1) + 5 / 10 ^ 41\\n"
COMMAND printf "scale = 45; 4 * a(1) + 5 / 10 ^ 41\\n"
Line 470: Line 479:
COMMAND sed -e "s/.\\{5\\}$//"
COMMAND sed -e "s/.\\{5\\}$//"
OUTPUT_VARIABLE pi OUTPUT_STRIP_TRAILING_WHITESPACE)
OUTPUT_VARIABLE pi OUTPUT_STRIP_TRAILING_WHITESPACE)
message(STATUS "pi is ${pi}")</lang>
message(STATUS "pi is ${pi}")</syntaxhighlight>


<pre>-- pi is 3.1415926535897932384626433832795028841972</pre>
<pre>-- pi is 3.1415926535897932384626433832795028841972</pre>
Line 476: Line 485:
=={{header|COBOL}}==
=={{header|COBOL}}==
{{works with|OpenCOBOL}}
{{works with|OpenCOBOL}}
<lang cobol>CALL "SYSTEM" USING BY CONTENT "ls"</lang>
<syntaxhighlight lang="cobol">CALL "SYSTEM" USING BY CONTENT "ls"</syntaxhighlight>


=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
{{works with|Node.js}}
{{works with|Node.js}}
<lang coffeescript>
<syntaxhighlight lang="coffeescript">
{ spawn } = require 'child_process'
{ spawn } = require 'child_process'


Line 490: Line 499:


ls.on 'close', -> console.log "'ls' has finished executing."
ls.on 'close', -> console.log "'ls' has finished executing."
</syntaxhighlight>
</lang>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
{{works with|CMUCL}}
{{works with|CMUCL}}
<lang lisp>(with-output-to-string (stream) (extensions:run-program "ls" nil :output stream))</lang>
<syntaxhighlight lang="lisp">(with-output-to-string (stream) (extensions:run-program "ls" nil :output stream))</syntaxhighlight>


{{works with|LispWorks}}
{{works with|LispWorks}}


<lang lisp>(system:call-system "ls")</lang>
<syntaxhighlight lang="lisp">(system:call-system "ls")</syntaxhighlight>


{{libheader|trivial-shell}}
{{libheader|trivial-shell}}


<lang lisp>(trivial-shell:shell-command "ls")</lang>
<syntaxhighlight lang="lisp">(trivial-shell:shell-command "ls")</syntaxhighlight>


{{libheader|uiop}}
{{libheader|uiop}}


<lang lisp>; uiop is part of the de facto build system, asdf, so should be available to most installations.
<syntaxhighlight lang="lisp">; uiop is part of the de facto build system, asdf, so should be available to most installations.


; synchronous
; synchronous
Line 513: Line 522:
; async
; async
(defparameter *process* (uiop:launch-program "ls"))
(defparameter *process* (uiop:launch-program "ls"))
(uiop:wait-process *process*)</lang>
(uiop:wait-process *process*)</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
<syntaxhighlight lang="d">
<lang d>
import std.process, std.stdio;
import std.process, std.stdio;
//these two alternatives wait for the process to return, and capture the output
//these two alternatives wait for the process to return, and capture the output
Line 526: Line 535:
writeln((ls_array.status == 0) ? ls_array.output : "command failed");
writeln((ls_array.status == 0) ? ls_array.output : "command failed");
//other alternatives exist to spawn processes in parallel and capture output via pipes
//other alternatives exist to spawn processes in parallel and capture output via pipes
</syntaxhighlight>
</lang>
std.process.system() is deprecated.
std.process.system() is deprecated.


=={{header|dc}}==
=={{header|dc}}==
<lang dc>! ls</lang>
<syntaxhighlight lang="dc">! ls</syntaxhighlight>




=={{header|DBL}}==
=={{header|DBL}}==
<lang DBL>XCALL SPAWN ("ls *.jpg > file.txt") ;execute command and continue
<syntaxhighlight lang="dbl">XCALL SPAWN ("ls *.jpg > file.txt") ;execute command and continue
XCALL EXEC ("script.sh") ;execute script or binary and exit
XCALL EXEC ("script.sh") ;execute script or binary and exit
STOP '@/bin/ls *.jpg > file.txt' ;exit and execute command</lang>
STOP '@/bin/ls *.jpg > file.txt' ;exit and execute command</syntaxhighlight>


=={{header|DCL}}==
=={{header|DCL}}==
<lang DCL>Directory</lang>
<syntaxhighlight lang="dcl">Directory</syntaxhighlight>
Or, shorter<lang DCL>dir</lang>
Or, shorter<syntaxhighlight lang="dcl">dir</syntaxhighlight>


=={{header|Delphi}}==
=={{header|Delphi}}==
<lang Delphi>program ExecuteSystemCommand;
<syntaxhighlight lang="delphi">program ExecuteSystemCommand;


{$APPTYPE CONSOLE}
{$APPTYPE CONSOLE}
Line 551: Line 560:
begin
begin
ShellExecute(0, nil, 'cmd.exe', ' /c dir', nil, SW_HIDE);
ShellExecute(0, nil, 'cmd.exe', ' /c dir', nil, SW_HIDE);
end.</lang>
end.</syntaxhighlight>


=={{header|E}}==
=={{header|E}}==
<lang e>def ls := makeCommand("ls")
<syntaxhighlight lang="e">def ls := makeCommand("ls")
ls("-l")
ls("-l")


Line 563: Line 572:
} catch problem {
} catch problem {
print(`failed to execute ls: $problem`)
print(`failed to execute ls: $problem`)
}</lang>
}</syntaxhighlight>


=={{header|Emacs Lisp}}==
=={{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}}==
=={{header|Erlang}}==
<lang erlang>os:cmd("ls").</lang>
<syntaxhighlight lang="erlang">os:cmd("ls").</syntaxhighlight>


=={{header|ERRE}}==
=={{header|ERRE}}==
Line 580: Line 592:
For example
For example


<lang> SHELL("DIR/W")</lang>
<syntaxhighlight lang="text"> SHELL("DIR/W")</syntaxhighlight>


lists the current directory and then returns to the program.
lists the current directory and then returns to the program.


<lang ERRE>cmd$="DIR/W"
<syntaxhighlight lang="erre">cmd$="DIR/W"
SHELL(cmd$)</lang>
SHELL(cmd$)</syntaxhighlight>


=={{header|Euphoria}}==
=={{header|Euphoria}}==
Euphoria has 2 systems command functions: '''system()''' and '''system_exec()'''.
Euphoria has 2 systems command functions: '''system()''' and '''system_exec()'''.
<lang euphoria> -- system --
<syntaxhighlight lang="euphoria"> -- system --
-- the simplest way --
-- the simplest way --
-- system spawns a new shell so I/O redirection is possible --
-- system spawns a new shell so I/O redirection is possible --
Line 620: Line 632:
else
else
printf( STDERR, "command %s failed with code %d\n", ls_command, exit_code)
printf( STDERR, "command %s failed with code %d\n", ls_command, exit_code)
end if</lang>
end if</syntaxhighlight>


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>System.Diagnostics.Process.Start("cmd", "/c dir")</lang>
<syntaxhighlight lang="fsharp">System.Diagnostics.Process.Start("cmd", "/c dir")</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>"ls" run-process wait-for-process</lang>
<syntaxhighlight lang="factor">"ls" run-process wait-for-process</syntaxhighlight>


=={{header|Fantom}}==
=={{header|Fantom}}==
Line 632: Line 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:
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>
<syntaxhighlight lang="fantom">
class Main
class Main
{
{
Line 641: Line 653:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|Forth}}==
=={{header|Forth}}==
{{works with|gforth|0.6.2}}
{{works with|gforth|0.6.2}}
<lang forth>s" ls" system</lang>
<syntaxhighlight lang="forth">s" ls" system</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
execute_command_line subroutine in Fortran 2008 and later runs a system command
execute_command_line subroutine in Fortran 2008 and later runs a system command
<lang fortran>
<syntaxhighlight lang="fortran">
program SystemTest
program SystemTest
integer :: i
integer :: i
call execute_command_line ("ls", exitstat=i)
call execute_command_line ("ls", exitstat=i)
end program SystemTest
end program SystemTest
</syntaxhighlight>
</lang>


{{works with|gfortran}}
{{works with|gfortran}}
The <tt>SYSTEM</tt> subroutine (and function) are a GNU extension.
The <tt>SYSTEM</tt> subroutine (and function) are a GNU extension.
<lang fortran>program SystemTest
<syntaxhighlight lang="fortran">program SystemTest
call system("ls")
call system("ls")
end program SystemTest</lang>
end program SystemTest</syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


Shell "dir"
Shell "dir"
Sleep</lang>
Sleep</syntaxhighlight>


=={{header|Frink}}==
=={{header|Frink}}==
<lang frink>r = callJava["java.lang.Runtime", "getRuntime"]
<syntaxhighlight lang="frink">r = callJava["java.lang.Runtime", "getRuntime"]
println[read[r.exec["dir"].getInputStream[]]]</lang>
println[read[r.exec["dir"].getInputStream[]]]</syntaxhighlight>


=={{header|FunL}}==
=={{header|FunL}}==
<lang funl>import sys.execute
<syntaxhighlight lang="funl">import sys.execute


execute( if $os.startsWith('Windows') then 'dir' else 'ls' )</lang>
execute( if $os.startsWith('Windows') then 'dir' else 'ls' )</syntaxhighlight>


=={{header|FutureBasic}}==
=={{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.
<lang futurebasic>
<syntaxhighlight lang="futurebasic">
print unix(@"ls -A")
include "ConsoleWindow"
</syntaxhighlight>

Classic FB using Pascal strings
<syntaxhighlight>
local fn DoUnixCommand( cmd as str255 )
local fn DoUnixCommand( cmd as str255 )
dim as str255 s
str255 s


open "Unix", 2, cmd
open "Unix", 2, cmd
Line 694: Line 708:


fn DoUnixCommand( "ls -A" )
fn DoUnixCommand( "ls -A" )
</syntaxhighlight>
</lang>


Output:
Output:
Line 723: Line 737:
usr
usr
var
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>
</pre>


=={{header|Gambas}}==
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=9460b39a86794a7346a390aeb50fc5cf Click this link to run this code]'''
'''[https://gambas-playground.proko.eu/?gist=9460b39a86794a7346a390aeb50fc5cf Click this link to run this code]'''
<lang gambas>Public Sub Main()
<syntaxhighlight lang="gambas">Public Sub Main()


Shell "ls -aul"
Shell "ls -aul"


End</lang>
End</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 745: Line 843:


=={{header|Genie}}==
=={{header|Genie}}==
<lang genie>[indent=4]
<syntaxhighlight lang="genie">[indent=4]
/*
/*
Execute system command, in Genie
Execute system command, in Genie
Line 758: Line 856:
Process.spawn_command_line_async("ls")
Process.spawn_command_line_async("ls")
except e : SpawnError
except e : SpawnError
stderr.printf("%s\n", e.message)</lang>
stderr.printf("%s\n", e.message)</syntaxhighlight>


{{out}}
{{out}}
Line 772: Line 870:
=={{header|gnuplot}}==
=={{header|gnuplot}}==


<lang gnuplot>!ls</lang>
<syntaxhighlight lang="gnuplot">!ls</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 790: Line 888:
log.Fatal(err)
log.Fatal(err)
}
}
}</lang>
}</syntaxhighlight>


=={{header|Groovy}}==
=={{header|Groovy}}==
<lang groovy>println "ls -la".execute().text</lang>
<syntaxhighlight lang="groovy">println "ls -la".execute().text</syntaxhighlight>


=={{header|GUISS}}==
=={{header|GUISS}}==


<lang guiss>Start,Programs,Accessories,MSDOS Prompt,Type:dir[enter]</lang>
<syntaxhighlight lang="guiss">Start,Programs,Accessories,MSDOS Prompt,Type:dir[enter]</syntaxhighlight>


=={{header|Haskell}}==
=={{header|Haskell}}==
{{works with|GHC|GHCi|6.6}}
{{works with|GHC|GHCi|6.6}}
<lang haskell>import System.Cmd
<syntaxhighlight lang="haskell">import System.Cmd


main = system "ls"
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
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}}==
=={{header|HicEst}}==
<lang hicest>SYSTEM(CoMmand='pause')
<syntaxhighlight lang="hicest">SYSTEM(CoMmand='pause')
SYSTEM(CoMmand='dir & pause') </lang>
SYSTEM(CoMmand='dir & pause') </syntaxhighlight>


=={{header|HolyC}}==
=={{header|HolyC}}==
Line 817: Line 915:
For example, to execute the <code>Dir</code> command:
For example, to execute the <code>Dir</code> command:


<lang holyc>Dir;</lang>
<syntaxhighlight lang="holyc">Dir;</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
The code below selects the 'ls' or 'dir' command at runtime based on the UNIX feature.
The code below selects the 'ls' or 'dir' command at runtime based on the UNIX feature.


<lang Icon>procedure main()
<syntaxhighlight lang="icon">procedure main()


write("Trying command ",cmd := if &features == "UNIX" then "ls" else "dir")
write("Trying command ",cmd := if &features == "UNIX" then "ls" else "dir")
system(cmd)
system(cmd)


end</lang>
end</syntaxhighlight>


Unicon extends system to allow specification of files and a wait/nowait parameter as in the examples below.
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,"wait")
pid := system(command_string,&input,&output,&errout,"nowait")
pid := system(command_string,&input,&output,&errout,"nowait")
</syntaxhighlight>
</lang>


=={{header|IDL}}==
=={{header|IDL}}==
<lang idl>$ls</lang>
<syntaxhighlight lang="idl">$ls</syntaxhighlight>


Will execute "ls" with output to the screen.
Will execute "ls" with output to the screen.


<lang idl>spawn,"ls",result</lang>
<syntaxhighlight lang="idl">spawn,"ls",result</syntaxhighlight>


will execute it and store the result in the string array "result".
will execute it and store the result in the string array "result".


<lang idl>spawn,"ls",unit=unit</lang>
<syntaxhighlight lang="idl">spawn,"ls",unit=unit</syntaxhighlight>


will execute it asynchronously and direct any output from it into the LUN "unit" from whence it can be read at any (later) time.
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}}==
=={{header|Io}}==
<lang io>System runCommand("ls") stdout println</lang>
<syntaxhighlight lang="io">System runCommand("ls") stdout println</syntaxhighlight>


=={{header|IS-BASIC}}==
=={{header|IS-BASIC}}==
<lang IS-BASIC>100 EXT "dir"</lang>
<syntaxhighlight lang="is-basic">100 EXT "dir"</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==


The system command interface in J is provided by the standard "task" script:
The system command interface in J is provided by the standard "task" script:
<lang j>load'task'
<syntaxhighlight lang="j">load'task'


NB. Execute a command and wait for it to complete
NB. Execute a command and wait for it to complete
Line 871: Line 969:
NB. and capture its stdout
NB. and capture its stdout
stdin =: 'blahblahblah'
stdin =: 'blahblahblah'
stdout =: stdin spawn 'grep blah'</lang>
stdout =: stdin spawn 'grep blah'</syntaxhighlight>


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.
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 877: Line 975:
=={{header|Java}}==
=={{header|Java}}==
{{works with|Java|1.5+}}
{{works with|Java|1.5+}}
<lang java5>import java.util.Scanner;
<syntaxhighlight lang="java5">import java.util.Scanner;
import java.io.*;
import java.io.*;


Line 891: Line 989:
}
}
}
}
}</lang>
}</syntaxhighlight>


{{works with|Java|1.4+}}
{{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)
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;
<syntaxhighlight lang="java">import java.io.IOException;
import java.io.InputStream;
import java.io.InputStream;


Line 933: Line 1,031:
}</lang>
}</syntaxhighlight>


And the right way, which uses threading to read the InputStream given by the process.
And the right way, which uses threading to read the InputStream given by the process.
<lang java>import java.io.IOException;
<syntaxhighlight lang="java">import java.io.IOException;
import java.io.InputStream;
import java.io.InputStream;


Line 999: Line 1,097:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
Line 1,005: Line 1,103:


{{works with|JScript}}
{{works with|JScript}}
<lang javascript>var shell = new ActiveXObject("WScript.Shell");
<syntaxhighlight lang="javascript">var shell = new ActiveXObject("WScript.Shell");
shell.run("cmd /c dir & pause");</lang>
shell.run("cmd /c dir & pause");</syntaxhighlight>


{{works with|Rhino}}
{{works with|Rhino}}
<lang javascript>runCommand("cmd", "/c", "dir", "d:\\");
<syntaxhighlight lang="javascript">runCommand("cmd", "/c", "dir", "d:\\");
print("===");
print("===");
var options = {
var options = {
Line 1,018: Line 1,116:
};
};
runCommand("cmd", options);
runCommand("cmd", options);
print(options.output);</lang>
print(options.output);</syntaxhighlight>


=={{header|Joy}}==
=={{header|Joy}}==
<lang joy>"ls" system.</lang>
<<syntaxhighlight lang="joy">"ls" system.</syntaxhighlight>


=={{header|Julia}}==
=={{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:
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:
<lang Julia>run(`ls`)</lang>
<syntaxhighlight lang="julia">run(`ls`)</syntaxhighlight>


{{out}}
{{out}}
Line 1,042: Line 1,140:


Execute "ls"
Execute "ls"
<lang K> \ls</lang>
<syntaxhighlight lang="k"> \ls</syntaxhighlight>


Execute "ls" and capture the output in the variable "r":
Execute "ls" and capture the output in the variable "r":
<lang K> r: 4:"ls"</lang>
<syntaxhighlight lang="k"> r: 4:"ls"</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.0.6
<syntaxhighlight lang="scala">// version 1.0.6


import java.util.Scanner
import java.util.Scanner
Line 1,057: Line 1,155:
while (it.hasNextLine()) println(it.nextLine())
while (it.hasNextLine()) println(it.nextLine())
}
}
}</lang>
}</syntaxhighlight>


=={{header|Lang5}}==
=={{header|Lang5}}==
For one-word commands:
For one-word commands:
<lang Lang5>'ls system</lang>
<syntaxhighlight lang="lang5">'ls system</syntaxhighlight>
For multi-word commands:
For multi-word commands:
<lang Lang5>"ls -a" system</lang>
<syntaxhighlight lang="lang5">"ls -a" system</syntaxhighlight>


=={{header|Lasso}}==
=={{header|Lasso}}==
<lang Lasso>local(
<syntaxhighlight lang="lasso">local(
path = file_forceroot,
path = file_forceroot,
ls = sys_process('/bin/ls', (:'-l', #path)),
ls = sys_process('/bin/ls', (:'-l', #path)),
Line 1,073: Line 1,171:
'<pre>'
'<pre>'
#ls -> read
#ls -> read
'</pre>'</lang>
'</pre>'</syntaxhighlight>
<pre>total 16
<pre>total 16
drwxr-xr-x 8 _lasso staff 272 Nov 10 08:13 mydir
drwxr-xr-x 8 _lasso staff 272 Nov 10 08:13 mydir
Line 1,083: Line 1,181:
In the LFE REPL:
In the LFE REPL:


<lang lisp>
<syntaxhighlight lang="lisp">
> (os:cmd "ls -alrt")
> (os:cmd "ls -alrt")
</syntaxhighlight>
</lang>


That will display output on a single line, with literal newlines.
That will display output on a single line, with literal newlines.
Line 1,091: Line 1,189:
For pretty output, compose with <code>io:format</code>:
For pretty output, compose with <code>io:format</code>:


<lang lisp>
<syntaxhighlight lang="lisp">
> (io:format (os:cmd "ls -alrt"))
> (io:format (os:cmd "ls -alrt"))
</syntaxhighlight>
</lang>


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
drive1$ = left$(Drives$,1)
drive1$ = left$(Drives$,1)
run "cmd.exe /";drive1$;" dir & pause"
run "cmd.exe /";drive1$;" dir & pause"
</lang>
</syntaxhighlight>


=={{header|Limbo}}==
=={{header|Limbo}}==
Line 1,107: Line 1,205:
This version passes its argument list through to ls:
This version passes its argument list through to ls:


<lang Limbo>implement Runls;
<syntaxhighlight lang="limbo">implement Runls;


include "sys.m"; sys: Sys;
include "sys.m"; sys: Sys;
Line 1,130: Line 1,228:
sys->fprint(sys->fildes(2), "runls: %s: %r", s);
sys->fprint(sys->fildes(2), "runls: %s: %r", s);
raise "fail:errors";
raise "fail:errors";
}</lang>
}</syntaxhighlight>


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.
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.
Line 1,136: Line 1,234:
=={{header|Lingo}}==
=={{header|Lingo}}==
{{libheader|Shell Xtra}}
{{libheader|Shell Xtra}}
<lang lingo>sx = xtra("Shell").new()
<syntaxhighlight lang="lingo">sx = xtra("Shell").new()
if the platform contains "win" then
if the platform contains "win" then
put sx.shell_cmd("dir")
put sx.shell_cmd("dir")
else
else
put sx.shell_cmd("ls")
put sx.shell_cmd("ls")
end if</lang>
end if</syntaxhighlight>


=={{header|Locomotive Basic}}==
=={{header|Locomotive Basic}}==
Line 1,147: Line 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):
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>
<syntaxhighlight lang="basic">LIST</syntaxhighlight>


=={{header|Logo}}==
=={{header|Logo}}==
{{works with|UCB Logo}}
{{works with|UCB Logo}}
The lines of output of the SHELL command are returned as a list.
The lines of output of the SHELL command are returned as a list.
<lang logo>print first butfirst shell [ls -a] ; ..</lang>
<syntaxhighlight lang="logo">print first butfirst shell [ls -a] ; ..</syntaxhighlight>


=={{header|Logtalk}}==
=={{header|Logtalk}}==
Using the standard library:
Using the standard library:
<lang logtalk>os::shell('ls -a').</lang>
<syntaxhighlight lang="logtalk">os::shell('ls -a').</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>-- just executing the command
<syntaxhighlight lang="lua">-- just executing the command
os.execute("ls")
os.execute("ls")


-- to execute and capture the output, use io.popen
-- to execute and capture the output, use io.popen
local f = io.popen("ls") -- store the output in a "file"
local f = io.popen("ls") -- store the output in a "file"
print( f:read("*a") ) -- print out the "file"'s content</lang>
print( f:read("*a") ) -- print out the "file"'s content</syntaxhighlight>

=={{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}}==
=={{header|M4}}==
<lang M4>syscmd(ifdef(`__windows__',`dir',`ls'))</lang>
<syntaxhighlight lang="m4">syscmd(ifdef(`__windows__',`dir',`ls'))</syntaxhighlight>


=={{header|Make}}==
=={{header|Make}}==
Line 1,174: Line 1,285:
in definition
in definition


<lang make>contents=$(shell cat foo)
<syntaxhighlight lang="make">contents=$(shell cat foo)
curdir=`pwd`</lang>
curdir=`pwd`</syntaxhighlight>


in target
in target


<lang make>mytarget:
<syntaxhighlight lang="make">mytarget:
cat foo | grep mytext</lang>
cat foo | grep mytext</syntaxhighlight>


=={{header|Maple}}==
=={{header|Maple}}==
<lang Maple>ssystem("dir");</lang>
<syntaxhighlight lang="maple">ssystem("dir");</syntaxhighlight>


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<lang Mathematica>Run["ls"]</lang>
<syntaxhighlight lang="mathematica">Run["ls"]</syntaxhighlight>


=={{header|MATLAB}}==
=={{header|MATLAB}}==
Line 1,192: Line 1,303:


Sample Usage:
Sample Usage:
<lang MATLAB>>> system('PAUSE')
<syntaxhighlight lang="matlab">>> system('PAUSE')


Press any key to continue . . .
Press any key to continue . . .
Line 1,200: Line 1,311:


0
0
</syntaxhighlight>
</lang>


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang>system("dir > list.txt")$</lang>
<syntaxhighlight lang="text">system("dir > list.txt")$</syntaxhighlight>


=={{header|MAXScript}}==
=={{header|MAXScript}}==
<lang maxscript>dosCommand "pause"</lang>
<syntaxhighlight lang="maxscript">dosCommand "pause"</syntaxhighlight>


=={{header|Mercury}}==
=={{header|Mercury}}==
<lang>
<syntaxhighlight lang="text">
:- module execute_sys_cmd.
:- module execute_sys_cmd.
:- interface.
:- interface.
Line 1,220: Line 1,331:
main(!IO) :-
main(!IO) :-
io.call_system("ls", _Result, !IO).
io.call_system("ls", _Result, !IO).
</syntaxhighlight>
</lang>


=={{header|min}}==
=={{header|min}}==
{{works with|min|0.19.3}}
{{works with|min|0.19.3}}
<lang min>!dir</lang>
<syntaxhighlight lang="min">!dir</syntaxhighlight>


=={{header|Modula-2}}==
=={{header|Modula-2}}==
<lang modula2>MODULE tri;
<syntaxhighlight lang="modula2">MODULE tri;


FROM SYSTEM IMPORT ADR;
FROM SYSTEM IMPORT ADR;
Line 1,260: Line 1,371:
InOut.WriteLn;
InOut.WriteLn;
InOut.WriteBf
InOut.WriteBf
END tri.</lang>
END tri.</syntaxhighlight>


=={{header|Modula-3}}==
=={{header|Modula-3}}==
Line 1,266: Line 1,377:


Also note the <code>EVAL</code> keyword, which ignores the return value of a function.
Also note the <code>EVAL</code> keyword, which ignores the return value of a function.
<lang modula3>UNSAFE MODULE Exec EXPORTS Main;
<syntaxhighlight lang="modula3">UNSAFE MODULE Exec EXPORTS Main;


IMPORT Unix, M3toC;
IMPORT Unix, M3toC;
Line 1,275: Line 1,386:
EVAL Unix.system(command);
EVAL Unix.system(command);
M3toC.FreeCopiedS(command);
M3toC.FreeCopiedS(command);
END Exec.</lang>
END Exec.</syntaxhighlight>


=={{header|MUMPS}}==
=={{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>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:
<p>In Caché on OpenVMS in an FILES-11 filesystem ODS-5 mode this could work:
<lang MUMPS>Set X=$ZF(-1,"DIR")</lang></p>
<syntaxhighlight lang="mumps">Set X=$ZF(-1,"DIR")</syntaxhighlight></p>


<p>In GT.M on OpenVMS, the following will work:
<p>In GT.M on OpenVMS, the following will work:
<lang MUMPS>ZSY "DIR"</lang></p>
<syntaxhighlight lang="mumps">ZSY "DIR"</syntaxhighlight></p>
<p>GT.M on UNIX is the same:
<p>GT.M on UNIX is the same:
<lang MUMPS>ZSY "ls"</lang></p>
<syntaxhighlight lang="mumps">ZSY "ls"</syntaxhighlight></p>
<p>Note: $ZF in GT.M is Unicode version of $F[ind].</p>
<p>Note: $ZF in GT.M is Unicode version of $F[ind].</p>


=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
<lang Nanoquery>shell("ls")</lang>
<syntaxhighlight lang="nanoquery">shell("ls")</syntaxhighlight>


=={{header|NetRexx}}==
=={{header|NetRexx}}==
{{Trans|Java}}
{{Trans|Java}}
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols binary
options replace format comments java crossref symbols binary


Line 1,301: Line 1,412:
return
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
method runSample(arg) private static
parse arg command
parse arg command
Line 1,316: Line 1,427:
end
end
return
return
</syntaxhighlight>
</lang>


=={{header|NewLISP}}==
=={{header|NewLISP}}==
<lang NewLISP>(exec "ls")</lang>
<syntaxhighlight lang="newlisp">(exec "ls")</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>import osproc
<syntaxhighlight lang="nim">import osproc


let exitCode = execCmd "ls"
let exitCode = execCmd "ls"
let (output, exitCode2) = execCmdEx "ls"</lang>
let (output, exitCode2) = execCmdEx "ls"</syntaxhighlight>


=={{header|Objective-C}}==
=={{header|Objective-C}}==
{{works with|GCC}}<br>
{{works with|GCC}}<br>
NSTask runs an external process with explicit path and arguments.
NSTask runs an external process with explicit path and arguments.
<lang objc>void runls()
<syntaxhighlight lang="objc">void runls()
{
{
[[NSTask launchedTaskWithLaunchPath:@"/bin/ls"
[[NSTask launchedTaskWithLaunchPath:@"/bin/ls"
arguments:@[]] waitUntilExit];
arguments:@[]] waitUntilExit];
}</lang>
}</syntaxhighlight>
If you need to run a system command, invoke the shell:
If you need to run a system command, invoke the shell:
<lang objc>void runSystemCommand(NSString *cmd)
<syntaxhighlight lang="objc">void runSystemCommand(NSString *cmd)
{
{
[[NSTask launchedTaskWithLaunchPath:@"/bin/sh"
[[NSTask launchedTaskWithLaunchPath:@"/bin/sh"
arguments:@[@"-c", cmd]]
arguments:@[@"-c", cmd]]
waitUntilExit];
waitUntilExit];
}</lang>
}</syntaxhighlight>
Complete usage example:
Complete usage example:


Line 1,347: Line 1,458:
{{works with|Cocoa}}<br>
{{works with|Cocoa}}<br>
{{works with|GNUstep}}
{{works with|GNUstep}}
<lang objc>#import <Foundation/Foundation.h>
<syntaxhighlight lang="objc">#import <Foundation/Foundation.h>


void runSystemCommand(NSString *cmd)
void runSystemCommand(NSString *cmd)
Line 1,363: Line 1,474:
}
}
return 0;
return 0;
}</lang>
}</syntaxhighlight>
Or use the C method above.
Or use the C method above.


Line 1,369: Line 1,480:
Just run the command:
Just run the command:


<lang ocaml>Sys.command "ls"</lang>
<syntaxhighlight lang="ocaml">Sys.command "ls"</syntaxhighlight>


To capture the output of the command:
To capture the output of the command:


<lang ocaml>#load "unix.cma"
<syntaxhighlight lang="ocaml">#load "unix.cma"


let syscall cmd =
let syscall cmd =
Line 1,386: Line 1,497:
(Buffer.contents buf)
(Buffer.contents buf)


let listing = syscall "ls" ;;</lang>
let listing = syscall "ls" ;;</syntaxhighlight>




a more complete version which also returns the contents from stderr, and checks the exit-status, and where the environment can be specified:
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
<syntaxhighlight lang="ocaml">let check_exit_status = function
| Unix.WEXITED 0 -> ()
| Unix.WEXITED 0 -> ()
| Unix.WEXITED r -> Printf.eprintf "warning: the process terminated with exit code (%d)\n%!" r
| Unix.WEXITED r -> Printf.eprintf "warning: the process terminated with exit code (%d)\n%!" r
Line 1,411: Line 1,522:
check_exit_status exit_status;
check_exit_status exit_status;
(Buffer.contents buf1,
(Buffer.contents buf1,
Buffer.contents buf2)</lang>
Buffer.contents buf2)</syntaxhighlight>


val syscall : ?env:string array -> string -> string * string
val syscall : ?env:string array -> string -> string * string


=={{header|Octave}}==
=={{header|Octave}}==
<lang octave>system("ls");</lang>
<syntaxhighlight lang="octave">system("ls");</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==


<lang Oforth>System cmd("pause")</lang>
<syntaxhighlight lang="oforth">System cmd("pause")</syntaxhighlight>


=={{header|Oz}}==
=={{header|Oz}}==
<lang oz>{OS.system "ls" _}</lang>
<syntaxhighlight lang="oz">{OS.system "ls" _}</syntaxhighlight>


A more sophisticated example can be found [http://www.mozart-oz.org/home/doc/op/node17.html here].
A more sophisticated example can be found [http://www.mozart-oz.org/home/doc/op/node17.html here].


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<lang parigp>system("ls")</lang>
<syntaxhighlight lang="parigp">system("ls")</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
{{works with|Free_Pascal}} {{libheader|SysUtils}}
{{works with|Free_Pascal}} {{libheader|SysUtils}}
<lang pascal>Program ExecuteSystemCommand;
<syntaxhighlight lang="pascal">Program ExecuteSystemCommand;


uses
uses
Line 1,438: Line 1,549:
begin
begin
ExecuteProcess('/bin/ls', '-alh');
ExecuteProcess('/bin/ls', '-alh');
end.</lang>
end.</syntaxhighlight>


=={{header|PDP-11 Assembly}}==
=={{header|PDP-11 Assembly}}==
PDP-11 running Unix
PDP-11 running Unix
<lang pdp-11>; Execute a file - the equivalent of system() in stdio
<syntaxhighlight lang="pdp-11">; Execute a file - the equivalent of system() in stdio
;
;
; On entry, r1=>nul-terminated command string
; On entry, r1=>nul-terminated command string
Line 1,499: Line 1,610:
EQUW 0
EQUW 0
EQUW 0
EQUW 0
EQUW 0</lang>
EQUW 0</syntaxhighlight>
So, call with, for example:
So, call with, for example:
<lang pdp-11>mov #cmd_ls,r1 ; => "ls" command string
<syntaxhighlight lang="pdp-11">mov #cmd_ls,r1 ; => "ls" command string
jsr pc,CLIsystem
jsr pc,CLIsystem
...
...
.cmd_ls EQUS "ls",0</lang>
.cmd_ls EQUS "ls",0</syntaxhighlight>


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>my @results = qx(ls); # run command and return STDOUT as a string
<syntaxhighlight lang="perl">my @results = qx(ls); # run command and return STDOUT as a string


my @results = `ls`; # same, alternative syntax
my @results = `ls`; # same, alternative syntax
Line 1,515: Line 1,626:
print `ls`; # same, but with back quotes
print `ls`; # same, but with back quotes


exec "ls"; # replace current process with another</lang>
exec "ls"; # replace current process with another</syntaxhighlight>


See also:
See also:
Line 1,522: Line 1,633:


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(notonline)-->
<!--<syntaxhighlight lang="phix">(notonline)-->
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span>
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span>
<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>
<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>
<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: #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>
<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>
<!--</lang>-->
<!--</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.
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}}==
=={{header|PHP}}==
The first line execute the command and the second line display the output:
The first line execute the command and the second line display the output:
<lang php>@exec($command,$output);
<syntaxhighlight lang="php">@exec($command,$output);
echo nl2br($output);</lang>
echo nl2br($output);</syntaxhighlight>
'''Note:'''The '@' is here to prevent error messages to be displayed, 'nl2br' translate '\n' chars to 'br' in HTML.
'''Note:'''The '@' is here to prevent error messages to be displayed, 'nl2br' translate '\n' chars to 'br' in HTML.


Other:
Other:
<lang php>$results = `ls`;
<syntaxhighlight lang="php">$results = `ls`;
# runs command and returns its STDOUT as a string
# runs command and returns its STDOUT as a string


Line 1,547: Line 1,658:


passthru("ls");
passthru("ls");
# like system() but binary-safe</lang>
# like system() but binary-safe</syntaxhighlight>


See also: [http://us.php.net/manual/en/function.proc-open.php proc_open()]
See also: [http://us.php.net/manual/en/function.proc-open.php proc_open()]


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(call "ls")</lang>
<syntaxhighlight lang="picolisp">(call "ls")</syntaxhighlight>


=={{header|Pike}}==
=={{header|Pike}}==
<lang pike>int main(){
<syntaxhighlight lang="pike">int main(){
// Process.run was added in Pike 7.8 as a wrapper to simplify the use of Process.create_process()
// 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");
mapping response = Process.run("ls -l");
Line 1,566: Line 1,677:
Process.create_process(({"ls", "-l"}), ([ "stdout" : stdout->pipe() ]) );
Process.create_process(({"ls", "-l"}), ([ "stdout" : stdout->pipe() ]) );
write(stdout->read() + "\n");
write(stdout->read() + "\n");
}</lang>
}</syntaxhighlight>

=={{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}}==
=={{header|Pop11}}==
The sysobey function runs commands using a shell:
The sysobey function runs commands using a shell:


<lang pop11>sysobey('ls');</lang>
<syntaxhighlight lang="pop11">sysobey('ls');</syntaxhighlight>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
Since PowerShell is a shell, running commands is the default operation.
Since PowerShell is a shell, running commands is the default operation.
<lang powershell>dir
<syntaxhighlight lang="powershell">dir
ls
ls
Get-ChildItem</lang>
Get-ChildItem</syntaxhighlight>
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
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
<lang powershell>cmd /c dir</lang>
<syntaxhighlight lang="powershell">cmd /c dir</syntaxhighlight>


=={{header|Prolog}}==
=={{header|Prolog}}==
Line 1,585: Line 1,714:


{{works with|GNU Prolog}}
{{works with|GNU Prolog}}
<lang prolog>shell('ls').</lang>
<syntaxhighlight lang="prolog">shell('ls').</syntaxhighlight>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>ImportC "msvcrt.lib"
<syntaxhighlight lang="purebasic">ImportC "msvcrt.lib"
system(str.p-ascii)
system(str.p-ascii)
EndImport
EndImport
Line 1,598: Line 1,727:
Input()
Input()
CloseConsole()
CloseConsole()
EndIf</lang>
EndIf</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
<lang python>import os
<syntaxhighlight lang="python">import os
exit_code = os.system('ls') # Just execute the command, return a success/fail code
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>
output = os.popen('ls').read() # If you want to get the output data. Deprecated.</syntaxhighlight>
or
or


{{works with|Python|2.7 (and above)}}
{{works with|Python|2.7 (and above)}}
<lang python>import subprocess
<syntaxhighlight lang="python">import subprocess
# if the exit code was non-zero these commands raise a CalledProcessError
# if the exit code was non-zero these commands raise a CalledProcessError
exit_code = subprocess.check_call(['ls', '-l']) # Python 2.5+
exit_code = subprocess.check_call(['ls', '-l']) # Python 2.5+
assert exit_code == 0
assert exit_code == 0
output = subprocess.check_output(['ls', '-l']) # Python 2.7+</lang>
output = subprocess.check_output(['ls', '-l']) # Python 2.7+</syntaxhighlight>


or
or


{{works with|Python|2.4 (and above)}}
{{works with|Python|2.4 (and above)}}
<lang python>from subprocess import PIPE, Popen, STDOUT
<syntaxhighlight lang="python">from subprocess import PIPE, Popen, STDOUT
p = Popen('ls', stdout=PIPE, stderr=STDOUT)
p = Popen('ls', stdout=PIPE, stderr=STDOUT)
print p.communicate()[0]</lang>
print p.communicate()[0]</syntaxhighlight>


'''Note:''' The latter is the preferred method for calling external processes, although cumbersome, it gives you finer control over the process.
'''Note:''' The latter is the preferred method for calling external processes, although cumbersome, it gives you finer control over the process.
Line 1,625: Line 1,754:


{{works with|Python|2.2 (and above)}}
{{works with|Python|2.2 (and above)}}
<lang python>import commands
<syntaxhighlight lang="python">import commands
stat, out = commands.getstatusoutput('ls')
stat, out = commands.getstatusoutput('ls')
if not stat:
if not stat:
print out</lang>
print out</syntaxhighlight>


=={{header|Quackery}}==
=={{header|Quackery}}==
Line 1,634: Line 1,763:
{{trans|Python}}
{{trans|Python}}


<syntaxhighlight lang="quackery">$ \
<lang Quackery>$ \
import os
import os
exit_code = os.system('ls')
exit_code = os.system('ls')
\ python</lang>
\ python</syntaxhighlight>


{{out}}
{{out}}
Line 1,648: Line 1,777:


=={{header|R}}==
=={{header|R}}==
<lang R>system("ls")
<syntaxhighlight lang="r">system("ls")
output=system("ls",intern=TRUE)</lang>
output=system("ls",intern=TRUE)</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
#lang racket


Line 1,667: Line 1,796:
;; avoid specifying the executable path
;; avoid specifying the executable path
(system* (find-executable-path "/bin/ls") "-l")
(system* (find-executable-path "/bin/ls") "-l")
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
<lang perl6>run "ls" orelse .die; # output to stdout
<syntaxhighlight lang="raku" line>run "ls" orelse .die; # output to stdout


my @ls = qx/ls/; # output to variable
my @ls = qx/ls/; # output to variable


my $cmd = 'ls';
my $cmd = 'ls';
@ls = qqx/$cmd/; # same thing with interpolation</lang>
@ls = qqx/$cmd/; # same thing with interpolation</syntaxhighlight>


=={{header|Raven}}==
=={{header|Raven}}==
Back tick string is auto executed:
Back tick string is auto executed:


<lang raven>`ls -la` as listing</lang>
<syntaxhighlight lang="raven">`ls -la` as listing</syntaxhighlight>


Or specifically on any string:
Or specifically on any string:


<lang raven>'ls -la' shell as listing</lang>
<syntaxhighlight lang="raven">'ls -la' shell as listing</syntaxhighlight>


=={{header|REBOL}}==
=={{header|REBOL}}==
<lang REBOL>; Capture output to string variable:
<syntaxhighlight lang="rebol">; Capture output to string variable:


x: "" call/output "dir" x
x: "" call/output "dir" x
Line 1,702: Line 1,831:
; The 'shell' refinement may be necessary to launch some programs.
; The 'shell' refinement may be necessary to launch some programs.


call/shell "notepad.exe"</lang>
call/shell "notepad.exe"</syntaxhighlight>


=={{header|Red}}==
=={{header|Red}}==
<lang red>
<syntaxhighlight lang="red">
call/show %pause ;The /show refinement forces the display of system's shell window (Windows only).
call/show %pause ;The /show refinement forces the display of system's shell window (Windows only).
call/show %dir
call/show %dir
call/show %notepad.exe</lang>
call/show %notepad.exe</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
Since REXX is a shell scripting language, it's easy to execute commands:
Since REXX is a shell scripting language, it's easy to execute commands:
<lang REXX>"dir /a:d"</lang>
<syntaxhighlight lang="rexx">"dir /a:d"</syntaxhighlight>


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
system("dir")
system("dir")
</syntaxhighlight>
</lang>


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>string = `ls`
<syntaxhighlight lang="ruby">string = `ls`
# runs command and returns its STDOUT as a string
# runs command and returns its STDOUT as a string
string = %x{ls}
string = %x{ls}
Line 1,737: Line 1,866:
io = IO.popen('ls')
io = IO.popen('ls')
# ... later
# ... later
io.each {|line| puts line}</lang>
io.each {|line| puts line}</syntaxhighlight>


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>print shell$("ls") ' prints the returned data from the OS
<syntaxhighlight lang="runbasic">print shell$("ls") ' prints the returned data from the OS
a$ = shell$("ls") ' holds returned data in a$</lang>
a$ = shell$("ls") ' holds returned data in a$</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>use std::process::Command;
<syntaxhighlight lang="rust">use std::process::Command;
fn main() {
fn main() {
let output = Command::new("ls").output().unwrap_or_else(|e| {
let output = Command::new("ls").output().unwrap_or_else(|e| {
Line 1,751: Line 1,880:
println!("{}", String::from_utf8_lossy(&output.stdout));
println!("{}", String::from_utf8_lossy(&output.stdout));
}
}
</syntaxhighlight>
</lang>


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>import scala.sys.process.Process
<syntaxhighlight lang="scala">import scala.sys.process.Process
Process("ls", Seq("-oa"))!</lang>
Process("ls", Seq("-oa"))!</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==
{{works with|Guile}}
{{works with|Guile}}
{{works with|Chicken Scheme}}
{{works with|Chicken Scheme}}
<lang scheme>(system "ls")</lang>
<syntaxhighlight lang="scheme">(system "ls")</syntaxhighlight>


=={{header|Seed7}}==
=={{header|Seed7}}==
Line 1,772: Line 1,901:
Anyway, the task was to use a system command, so here is the example:
Anyway, the task was to use a system command, so here is the example:


<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "shell.s7i";
include "shell.s7i";


Line 1,778: Line 1,907:
begin
begin
cmd_sh("ls");
cmd_sh("ls");
end func;</lang>
end func;</syntaxhighlight>


=={{header|SETL}}==
=={{header|SETL}}==
<lang SETL>system("ls");</lang>
<syntaxhighlight lang="setl">system("ls");</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby># Pipe in read-only mode
<syntaxhighlight lang="ruby"># Pipe in read-only mode
%p(ls).open_r.each { |line|
%p(ls).open_r.each { |line|
print line;
print line;
Line 1,793: Line 1,922:


Sys.system('ls'); # system: executes a command and prints the result
Sys.system('ls'); # system: executes a command and prints the result
Sys.exec('ls'); # replaces current process with another</lang>
Sys.exec('ls'); # replaces current process with another</syntaxhighlight>


=={{header|Slate}}==
=={{header|Slate}}==
Line 1,799: Line 1,928:
Run a command normally through the shell:
Run a command normally through the shell:
<lang slate>Platform run: 'ls'.</lang>
<syntaxhighlight lang="slate">Platform run: 'ls'.</syntaxhighlight>


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):
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>
<syntaxhighlight lang="slate">shell ls: '*.slate'.</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==


<lang smalltalk>Smalltalk system: 'ls'.</lang>
<syntaxhighlight lang="smalltalk">Smalltalk system: 'ls'.</syntaxhighlight>


=={{header|SQL PL}}==
=={{header|SQL PL}}==
{{works with|Db2 LUW}}
{{works with|Db2 LUW}}
In Linux or UNIX:
In Linux or UNIX:
<lang sql pl>
<syntaxhighlight lang="sql pl">
!ls
!ls
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 1,830: Line 1,959:
</pre>
</pre>
In Windows:
In Windows:
<lang sql pl>
<syntaxhighlight lang="sql pl">
!dir
!dir
</syntaxhighlight>
</lang>


=={{header|Standard ML}}==
=={{header|Standard ML}}==
Just run the command:
Just run the command:


<lang sml>OS.Process.system "ls"</lang>
<syntaxhighlight lang="sml">OS.Process.system "ls"</syntaxhighlight>


=={{header|Stata}}==
=={{header|Stata}}==
Line 1,844: Line 1,973:
The command '''!''' (or equivalently '''shell'''), opens a Windows console to run the command, while '''winexec''' does not.
The command '''!''' (or equivalently '''shell'''), opens a Windows console to run the command, while '''winexec''' does not.


<lang stata>!dir
<syntaxhighlight lang="stata">!dir


* print a message and wait
* print a message and wait
Line 1,856: Line 1,985:


* load Windows Notepad
* load Windows Notepad
winexec notepad</lang>
winexec notepad</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==


<lang tcl>puts [exec ls]</lang>
<syntaxhighlight lang="tcl">puts [exec ls]</syntaxhighlight>


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.
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,866: Line 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:
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>
<syntaxhighlight lang="tcl">set io [open "|ls" r]</syntaxhighlight>


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:
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>
<syntaxhighlight lang="tcl">set nextline [gets $io]</syntaxhighlight>
or read the whole shebang in a fell swoop:
or read the whole shebang in a fell swoop:


<lang tcl>set lsoutput [read $io]</lang>
<syntaxhighlight lang="tcl">set lsoutput [read $io]</syntaxhighlight>


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.
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.


<lang tcl>exec C:/Windows/System32/taskmgr.exe &</lang>
<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.
Runs the Task Manager on Windows. If running from a Tcl/Tk Gui the [ & ] prevents blocking the Gui.


=={{header|Toka}}==
=={{header|Toka}}==
<lang toka>needs shell
<syntaxhighlight lang="toka">needs shell
" ls" system</lang>
" ls" system</syntaxhighlight>


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<lang tuscript>
<syntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
$$ MODE TUSCRIPT
system=SYSTEM ()
system=SYSTEM ()
Line 1,895: Line 2,024:
EXECUTE "ls -l"
EXECUTE "ls -l"
ENDIF
ENDIF
</syntaxhighlight>
</lang>


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
UNIX shells are designed to run system commands as a default operation.
UNIX shells are designed to run system commands as a default operation.
<lang bash>ls</lang>
<syntaxhighlight lang="bash">ls</syntaxhighlight>


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.
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>
<syntaxhighlight lang="bash">exec ls</syntaxhighlight>


===Command substitution===
===Command substitution===
Line 1,909: Line 2,038:


With [[Bourne Shell]]:
With [[Bourne Shell]]:
<lang bash>output=`ls`</lang>
<syntaxhighlight lang="bash">output=`ls`</syntaxhighlight>


With [[Korn Shell]] or any modern shell:
With [[Korn Shell]] or any modern shell:
<lang bash>output=$(ls)</lang>
<syntaxhighlight lang="bash">output=$(ls)</syntaxhighlight>


* '''Note 1:''' in <code>`ls`</code>, these are "backticks" rather than quotes or apostrophes.
* '''Note 1:''' in <code>`ls`</code>, these are "backticks" rather than quotes or apostrophes.
Line 1,920: Line 2,049:
The '''`...`''' form is difficult to nest, but the '''$(...)''' form is very nestable.
The '''`...`''' form is difficult to nest, but the '''$(...)''' form is very nestable.


<lang bash>output=`expr \`echo hi | wc -c\` - 1`
<syntaxhighlight lang="bash">output=`expr \`echo hi | wc -c\` - 1`
output=$(expr $(echo hi | wc -c) - 1)</lang>
output=$(expr $(echo hi | wc -c) - 1)</syntaxhighlight>


Both forms, `backticks` and '''$(...)''', also work inside double-quoted strings. This prevents file name expansion and also prevents word splitting.
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`"
<syntaxhighlight lang="bash">echo "Found: `grep 80/tcp /etc/services`"
echo "Found: $(grep 80/tcp /etc/services)"</lang>
echo "Found: $(grep 80/tcp /etc/services)"</syntaxhighlight>


==={{header|C Shell}}===
==={{header|C Shell}}===
C Shell also runs system commands, and has an '''exec''' built-in command, exactly like Bourne 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
<syntaxhighlight lang="csh">ls # run command, return to shell
exec ls # replace shell with command</lang>
exec ls # replace shell with command</syntaxhighlight>


`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.
`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`" )
<syntaxhighlight lang="csh">set output=( "`grep 80/ /etc/services`" )
echo "Line 1: $output[1]"
echo "Line 1: $output[1]"
echo "Line 2: $output[2]"</lang>
echo "Line 2: $output[2]"</syntaxhighlight>


=={{header|Ursa}}==
=={{header|Ursa}}==
<lang ursa>decl string<> arg
<syntaxhighlight lang="ursa">decl string<> arg
decl string<> output
decl string<> output
decl iodevice iod
decl iodevice iod
Line 1,951: Line 2,080:
for (decl int i) (< i (size output)) (inc i)
for (decl int i) (< i (size output)) (inc i)
out output<i> endl console
out output<i> endl console
end for</lang>
end for</syntaxhighlight>


=={{header|Ursala}}==
=={{header|Ursala}}==
Line 1,963: Line 2,092:
Here is a self-contained command line application providing a limited replacement
Here is a self-contained command line application providing a limited replacement
for the ls command.
for the ls command.
<lang Ursala>#import std
<syntaxhighlight lang="ursala">#import std
#import cli
#import cli


#executable ('parameterized','')
#executable ('parameterized','')


myls = <.file$[contents: --<''>]>@hm+ (ask bash)/0+ -[ls --color=no]-!</lang>
myls = <.file$[contents: --<''>]>@hm+ (ask bash)/0+ -[ls --color=no]-!</syntaxhighlight>
The color option is needed to suppress terminal escape sequences.
The color option is needed to suppress terminal escape sequences.


=={{header|VBScript}}==
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
Set objShell = CreateObject("WScript.Shell")
Set objShell = CreateObject("WScript.Shell")
objShell.Run "%comspec% /K dir",3,True
objShell.Run "%comspec% /K dir",3,True
</syntaxhighlight>
</lang>


=={{header|Vedit macro language}}==
=={{header|Vedit macro language}}==


<lang vedit>system("dir", DOS)</lang>
<syntaxhighlight lang="vedit">system("dir", DOS)</syntaxhighlight>


The above does not work on 64-bit Windows versions which do not have 16-bit DOS emulation.
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:
In this case, you need to call cmd.exe explicitly:


<lang vedit>system('cmd /k "dir"')</lang>
<syntaxhighlight lang="vedit">system('cmd /k "dir"')</syntaxhighlight>


=={{header|Visual Basic}}==
=={{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
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.
is probably the usual case. But it is possible.
<lang vb>Attribute VB_Name = "mdlShellAndWait"
<syntaxhighlight lang="vb">Attribute VB_Name = "mdlShellAndWait"
Option Explicit
Option Explicit


Line 2,064: Line 2,193:
Sub SpawnDir()
Sub SpawnDir()
ShellAndWait("dir", 10)
ShellAndWait("dir", 10)
End Sub</lang>
End Sub</syntaxhighlight>


=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
{{works with|Visual Basic .NET|9.0+}}
{{works with|Visual Basic .NET|9.0+}}
<lang vbnet>Module System_Command
<syntaxhighlight lang="vbnet">Module System_Command


Sub Main()
Sub Main()
Line 2,088: Line 2,217:


End Module
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}}==
=={{header|Wart}}==
<lang wart>system "ls"</lang>
<syntaxhighlight lang="wart">system "ls"</syntaxhighlight>


=={{header|Wren}}==
=={{header|Wren}}==
Line 2,098: Line 2,238:
However, if Wren is embedded in (say) a suitable Go program, then we can ask the latter to do it for us.
However, if Wren is embedded in (say) a suitable Go program, then we can ask the latter to do it for us.


<lang ecmascript>/* run_system_command.wren */
<syntaxhighlight lang="wren">/* Execute_a_system_command.wren */
class Command {
class Command {
foreign static exec(name, param) // the code for this is provided by Go
foreign static exec(name, param) // the code for this is provided by Go
Line 2,105: Line 2,245:
Command.exec("ls", "-lt")
Command.exec("ls", "-lt")
System.print()
System.print()
Command.exec("dir", "")</lang>
Command.exec("dir", "")</syntaxhighlight>


which we embed in the following Go program and run it.
which we embed in the following Go program and run it.
{{libheader|WrenGo}}
{{libheader|WrenGo}}
<lang go>/* run_system_command.go*/
<syntaxhighlight lang="go">/* Execute_a_system_command.go*/
package main
package main


Line 2,140: Line 2,280:
func main() {
func main() {
vm := wren.NewVM()
vm := wren.NewVM()
fileName := "run_system_command.wren"
fileName := "Execute_a_system_command.wren"
methodMap := wren.MethodMap{"static exec(_,_)": execCommand}
methodMap := wren.MethodMap{"static exec(_,_)": execCommand}
classMap := wren.ClassMap{"Command": wren.NewClass(nil, nil, methodMap)}
classMap := wren.ClassMap{"Command": wren.NewClass(nil, nil, methodMap)}
Line 2,147: Line 2,287:
vm.InterpretFile(fileName)
vm.InterpretFile(fileName)
vm.Free()
vm.Free()
}</lang>
}</syntaxhighlight>


=={{header|x86 Assembly}}==
=={{header|x86 Assembly}}==
Line 2,153: Line 2,293:
{{works with|Linux}}
{{works with|Linux}}
32 bit
32 bit
<lang asm>
<syntaxhighlight lang="asm">
; Executes '/bin/ls'
; Executes '/bin/ls'
; Build with:
; Build with:
Line 2,172: Line 2,312:
.path:
.path:
db '/bin/ls', 0x00
db '/bin/ls', 0x00
</syntaxhighlight>
</lang>

=={{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}}==
=={{header|zkl}}==
<lang zkl>System.cmd(System.isWindows and "dir" or "ls")</lang>
<syntaxhighlight lang="zkl">System.cmd(System.isWindows and "dir" or "ls")</syntaxhighlight>


=={{header|ZX Spectrum Basic}}==
=={{header|ZX Spectrum Basic}}==
Line 2,181: Line 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:
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>
<syntaxhighlight lang="zxbasic">PAUSE 100</syntaxhighlight>


{{omit from|EasyLang}}
{{omit from|Retro}}
{{omit from|Retro}}
{{omit from|TI-83 BASIC}} {{omit from|TI-89 BASIC}} <!-- Does not have an external OS/command processor. -->
{{omit from|TI-83 BASIC}} {{omit from|TI-89 BASIC}} <!-- Does not have an external OS/command processor. -->

Latest revision as of 17:34, 30 November 2023

Task
Execute a system command
You are encouraged to solve this task according to the task description, using any language you may know.
Task

Run either the   ls   system command   (dir   on Windows),   or the   pause   system command.

Related task



11l

os:(‘pause’)

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.

*&---------------------------------------------------------------------*
*& Report  ZEXEC_SYS_CMD
*&
*&---------------------------------------------------------------------*
*&
*&
*&---------------------------------------------------------------------*

REPORT  zexec_sys_cmd.

DATA: lv_opsys      TYPE          syst-opsys,
      lt_sxpgcotabe TYPE TABLE OF sxpgcotabe,
      ls_sxpgcotabe LIKE LINE OF  lt_sxpgcotabe,
      ls_sxpgcolist TYPE          sxpgcolist,
      lv_name       TYPE          sxpgcotabe-name,
      lv_opcommand  TYPE          sxpgcotabe-opcommand,
      lv_index      TYPE          c,
      lt_btcxpm     TYPE TABLE OF btcxpm,
      ls_btcxpm     LIKE LINE OF  lt_btcxpm
      .

* Initialize
lv_opsys = sy-opsys.
CLEAR lt_sxpgcotabe[].

IF lv_opsys EQ 'Windows NT'.
  lv_opcommand = 'dir'.
ELSE.
  lv_opcommand = 'ls'.
ENDIF.

* Check commands
SELECT * FROM sxpgcotabe INTO TABLE lt_sxpgcotabe
  WHERE opsystem  EQ lv_opsys
    AND opcommand EQ lv_opcommand.

IF lt_sxpgcotabe IS INITIAL.
  CLEAR ls_sxpgcolist.
  CLEAR lv_name.
  WHILE lv_name IS INITIAL.
* Don't mess with other users' commands
    lv_index = sy-index.
    CONCATENATE 'ZLS' lv_index INTO lv_name.
    SELECT * FROM sxpgcostab INTO ls_sxpgcotabe
      WHERE name EQ lv_name.
    ENDSELECT.
    IF sy-subrc = 0.
      CLEAR lv_name.
    ENDIF.
  ENDWHILE.
  ls_sxpgcolist-name      = lv_name.
  ls_sxpgcolist-opsystem  = lv_opsys.
  ls_sxpgcolist-opcommand = lv_opcommand.
* Create own ls command when nothing is declared
  CALL FUNCTION 'SXPG_COMMAND_INSERT'
    EXPORTING
      command                = ls_sxpgcolist
      public                 = 'X'
    EXCEPTIONS
      command_already_exists = 1
      no_permission          = 2
      parameters_wrong       = 3
      foreign_lock           = 4
      system_failure         = 5
      OTHERS                 = 6.
  IF sy-subrc <> 0.
* Implement suitable error handling here
  ELSE.
* Hooray it worked! Let's try to call it
    CALL FUNCTION 'SXPG_COMMAND_EXECUTE_LONG'
      EXPORTING
        commandname                   = lv_name
      TABLES
        exec_protocol                 = lt_btcxpm
      EXCEPTIONS
        no_permission                 = 1
        command_not_found             = 2
        parameters_too_long           = 3
        security_risk                 = 4
        wrong_check_call_interface    = 5
        program_start_error           = 6
        program_termination_error     = 7
        x_error                       = 8
        parameter_expected            = 9
        too_many_parameters           = 10
        illegal_command               = 11
        wrong_asynchronous_parameters = 12
        cant_enq_tbtco_entry          = 13
        jobcount_generation_error     = 14
        OTHERS                        = 15.
    IF sy-subrc <> 0.
* Implement suitable error handling here
      WRITE: 'Cant execute ls - '.
      CASE sy-subrc.
        WHEN 1.
          WRITE: / ' no permission!'.
        WHEN 2.
          WRITE: / ' command could not be created!'.
        WHEN 3.
          WRITE: / ' parameter list too long!'.
        WHEN 4.
          WRITE: / ' security risk!'.
        WHEN 5.
          WRITE: / ' wrong call of SXPG_COMMAND_EXECUTE_LONG!'.
        WHEN 6.
          WRITE: / ' command cant be started!'.
        WHEN 7.
          WRITE: / ' program terminated!'.
        WHEN 8.
          WRITE: / ' x_error!'.
        WHEN 9.
          WRITE: / ' parameter missing!'.
        WHEN 10.
          WRITE: / ' too many parameters!'.
        WHEN 11.
          WRITE: / ' illegal command!'.
        WHEN 12.
          WRITE: / ' wrong asynchronous parameters!'.
        WHEN 13.
          WRITE: / ' cant enqueue job!'.
        WHEN 14.
          WRITE: / ' cant create job!'.
        WHEN 15.
          WRITE: / ' unknown error!'.
        WHEN OTHERS.
          WRITE: / ' unknown error!'.
      ENDCASE.
    ELSE.
      LOOP AT lt_btcxpm INTO ls_btcxpm.
        WRITE: / ls_btcxpm.
      ENDLOOP.
    ENDIF.
  ENDIF.
ENDIF.

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;

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)

Aime

sshell ss;

ss.argv.insert("ls");

o_(ss.link);

ALGOL 68

Works with: ALGOL 68G version Any - tested with release mk15-0.8b.fc9 - "system" is not part of the standard's prelude.
system("ls")

Or the classic "!" shell escape can be implemented as an "!" operator:

Works with: ALGOL 68G version Any - tested with release mk15-0.8b.fc9 - "system" & "ANDF" are not part of the standard's prelude.
OP ! = (STRING cmd)BOOL: system(cmd) = 0;

IF ! "touch test.tmp" ANDF ( ! "ls test.tmp" ANDF ! "rm test.tmp" ) THEN
  print (("test.tmp now gone!", new line))
FI


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

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

AppleScript

do shell script "ls" without altering line endings

Applesoft BASIC

? CHR$(4)"CATALOG"

Arturo

print execute "ls"

AutoHotkey

Run, %comspec% /k dir & pause

AutoIt

Run(@ComSpec & " /c " & 'pause', "", @SW_HIDE)

AWK

Using system() function:

BEGIN {
  system("ls")		# Unix
 #system("dir")		# DOS/MS-Windows
}

Using getline command:

BEGIN {
         ls = sys2var("ls")
         print ls
}
function sys2var(command        ,fish, scale, ship) {
         command = command " 2>/dev/null"
         while ( (command | getline fish) > 0 ) {
             if ( ++scale == 1 )
                 ship = fish
             else
                 ship = ship "\n" fish
         }
         close(command)
         return ship
}

BASIC

SHELL "dir"

BaCon

' Execute a system command
SYSTEM "ls"

BASIC256

system "dir"

Batch File

dir

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"

Befunge

Works with: Befunge version 98

Works with any Funge-98 on Unix, try https://tio.run/##S0pNK81LT9W1tNAtqAQz//9XKs5RsnX4/x8A

"sl"=@;pushes ls, = executes it, @ ends it;


BQN

•SH is a function defined in the BQN spec, which provides output from a shell command.

The arguments to •SH are the command, followed by its arguments as a flat list of strings. For example:

•SH "ls"

Will give an output as a list of three elements: the command's exit code, text written to stdout, and text written to stderr.

Bracmat

sys$dir

Brat

include :subprocess 

p subprocess.run :ls  #Lists files in directory

Brlcad

exec ls

C

ISO C & POSIX:

#include <stdlib.h>

int main()
{
    system("ls");
    return 0;
}

C#

Using Windows / .NET:

using System.Diagnostics;

namespace Execute
{
    class Program
    {
        static void Main(string[] args)
        {
            Process.Start("cmd.exe", "/c dir");
        }
    }
}
Works with: MCS version 1.2.3.1
using System;
 
  class Execute {
     static void Main() {
         System.Diagnostics.Process proc = new System.Diagnostics.Process();
         proc.EnableRaisingEvents=false;
         proc.StartInfo.FileName="ls";
         proc.Start();
    }
 }

C++

Works with: Visual C++ version 2005
system("pause");

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

CMake

Works with: Unix
execute_process(COMMAND ls)

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 pipeeline, 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

COBOL

Works with: OpenCOBOL
CALL "SYSTEM" USING BY CONTENT "ls"

CoffeeScript

Works with: Node.js
{ 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."

Common Lisp

Works with: CMUCL
(with-output-to-string (stream) (extensions:run-program "ls" nil :output stream))
Works with: LispWorks
(system:call-system "ls")
Library: trivial-shell
(trivial-shell:shell-command "ls")
Library: uiop
; 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*)

D

import std.process, std.stdio;
//these two alternatives wait for the process to return, and capture the output
//each process function returns a Tuple of (int)"status" and (string)"output
auto ls_string = executeShell("ls -l"); //takes single string
writeln((ls_string.status == 0) ? ls_string.output : "command failed");

auto ls_array = execute(["ls", "-l"]); //takes array of strings
writeln((ls_array.status == 0) ? ls_array.output : "command failed");
//other alternatives exist to spawn processes in parallel and capture output via pipes

std.process.system() is deprecated.

dc

! ls


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

DCL

Directory

Or, shorter

dir

Delphi

program ExecuteSystemCommand;

{$APPTYPE CONSOLE}

uses Windows, ShellApi;

begin
  ShellExecute(0, nil, 'cmd.exe', ' /c dir', nil, SW_HIDE);
end.

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`)
}

Emacs Lisp

Synchronously (shell, interactive):

(shell-command "ls")

Asynchronously (shell, interactive):

(async-shell-command "ls")

Erlang

os:cmd("ls").

ERRE

In ERRE language you have the SHELL command followed, eventually, by a string command. SHELL itself opens a new DOS/Windows shell: you must use EXIT to end. For example

 SHELL("DIR/W")

lists the current directory and then returns to the program.

cmd$="DIR/W"
SHELL(cmd$)

Euphoria

Euphoria has 2 systems command functions: system() and system_exec().

 -- system --
-- the simplest way --
-- system spawns a new shell so I/O redirection is possible --

system( "dir /w c:\temp\ " ) -- Microsoft --

system( "/bin/ls -l /tmp" ) -- Linux BSD OSX --

----

 -- system_exec() --                                                                                                                                         
 -- system_exec does not spawn a new shell --                                                                                                                  
 -- ( like bash or cmd.exe ) --                                                                                                                                 

integer exit_code = 0
sequence ls_command = ""

ifdef UNIX or LINUX or OSX then
    ls_command = "/bin/ls -l "
elsifdef WINDOWS then
    ls_command = "dir /w "
end ifdef

exit_code = system_exec( ls_command )

if exit_code = -1 then
    puts( STDERR, " could not execute " & ls_command & "\n" )
elsif exit_code = 0 then
    puts( STDERR, ls_command & " succeeded\n")
else
    printf( STDERR, "command %s failed with code %d\n", ls_command, exit_code)
end if

F#

System.Diagnostics.Process.Start("cmd", "/c dir")

Factor

"ls" run-process wait-for-process

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
  }
}

Forth

Works with: gforth version 0.6.2
s" ls" system

Fortran

execute_command_line subroutine in Fortran 2008 and later runs a system command

program SystemTest
integer :: i
 call execute_command_line ("ls", exitstat=i)
end program SystemTest
Works with: gfortran

The SYSTEM subroutine (and function) are a GNU extension.

program SystemTest
  call system("ls")
end program SystemTest

FreeBASIC

' FB 1.05.0 Win64

Shell "dir"
Sleep

Frink

r = callJava["java.lang.Runtime", "getRuntime"]
println[read[r.exec["dir"].getInputStream[]]]

FunL

import sys.execute

execute( if $os.startsWith('Windows') then 'dir' else 'ls' )

FutureBasic

FB 7.0.23+

print unix(@"ls -A")

Classic FB using Pascal strings

local fn DoUnixCommand( cmd as str255 )
  str255 s

  open "Unix", 2, cmd
  while ( not eof(2) )
    line input #2, s
    print s
  wend
  close 2
end fn

fn DoUnixCommand( "ls -A" )

Output:

.DocumentRevisions-V100
.Spotlight-V100
.Trashes
.file
.fseventsd
.hotfiles.btree
.vol
Applications
Library
Network
System
Users
Volumes
bin
cores
dev
etc
home
mach_kernel
net
private
sbin
tmp
usr
var

Modern FB using CFStrings

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
Output:
                             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                    
                  

Gambas

Click this link to run this code

Public Sub Main()

Shell "ls -aul"

End

Output:

total 36364
drwxr-xr-x  88 charlie charlie     4096 May 29 10:26 .
drwxr-xr-x   5 root    root        4096 May 26 15:44 ..
drwxr-xr-x   2 charlie charlie     4096 May 29 10:54 15PuzzleGame
drwx------   3 charlie charlie     4096 May 28 13:51 .adobe
drwxr-xr-x   4 charlie charlie     4096 May 28 13:52 .audacity-data
drwxr-xr-x   4 charlie charlie     4096 May 28 13:51 .barcode
etc....

Genie

[indent=4]
/*
  Execute system command, in Genie

  valac executeSystemCommand.gs
  ./executeSystemCommand
*/

init
    try
        // Non Blocking
        Process.spawn_command_line_async("ls")
    except e : SpawnError
        stderr.printf("%s\n", e.message)
Output:

Output is asynchronous (could be made synchronous with spawn_command_line_sync), and elided here for the sample capture.

prompt$ valac executeSystemCommand.gs
prompt$ ./executeSystemCommand
...
aplusb            executeSystemCommand       hello.gs          helloNoNewline.gs
memavail          progress-bar               readfile.vapi     stringsample.vala
...

gnuplot

!ls

Go

package main

import (
    "log"
    "os"
    "os/exec"
)

func main() {
    cmd := exec.Command("ls", "-l")
    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr
    if err := cmd.Run(); err != nil {
        log.Fatal(err)
    }
}

Groovy

println "ls -la".execute().text

GUISS

Start,Programs,Accessories,MSDOS Prompt,Type:dir[enter]

Haskell

Works with: GHCi version 6.6
import System.Cmd

main = system "ls"

See also: the System.Process module

HicEst

SYSTEM(CoMmand='pause')
SYSTEM(CoMmand='dir & pause')

HolyC

HolyC is the official programming language for The Temple Operating System (TempleOS). The Temple Operating System interpreter executes just-in-time compiled HolyC code. All HolyC code is effectively executed as system commands.

For example, to execute the Dir command:

Dir;

Icon and Unicon

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")

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.

Io

System runCommand("ls") stdout println

IS-BASIC

100 EXT "dir"

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'

Note that on unix systems, you can also use the 2!:x family of foreign verbs to execute system commands.

Java

Works with: Java version 1.5+
import java.util.Scanner;
import java.io.*;

public class Program {
    public static void main(String[] args) {    	
    	try {
    		Process p = Runtime.getRuntime().exec("cmd /C dir");//Windows command, use "ls -oa" for UNIX
    		Scanner sc = new Scanner(p.getInputStream());    		
    		while (sc.hasNext()) System.out.println(sc.nextLine());
    	}
    	catch (IOException e) {
    		System.out.println(e.getMessage());
    	}
    }
}
Works with: Java version 1.4+

There are two ways to run system commands. The simple way, which will hang the JVM (I would be interested in some kind of reason). -- this happens because the the inputStream buffer fills up and blocks until it gets read. Moving your .waitFor after reading the InputStream would fix your issue (as long as your error stream doesn't fill up)

import java.io.IOException;
import java.io.InputStream;

public class MainEntry {
    public static void main(String[] args) {
        executeCmd("ls -oa");
    }

    private static void executeCmd(String string) {
        InputStream pipedOut = null;
        try {
            Process aProcess = Runtime.getRuntime().exec(string);
            aProcess.waitFor();

            pipedOut = aProcess.getInputStream();
            byte buffer[] = new byte[2048];
            int read = pipedOut.read(buffer);
            // Replace following code with your intends processing tools
            while(read >= 0) {
                System.out.write(buffer, 0, read);
                
                read = pipedOut.read(buffer);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException ie) {
            ie.printStackTrace();
        } finally {
            if(pipedOut != null) {
                try {
                    pipedOut.close();
                } catch (IOException e) {
                }
            }
        }
    }
    
    
}

And the right way, which uses threading to read the InputStream given by the process.

import java.io.IOException;
import java.io.InputStream;

public class MainEntry {
    public static void main(String[] args) {
        // the command to execute
        executeCmd("ls -oa");
    }

    private static void executeCmd(String string) {
        InputStream pipedOut = null;
        try {
            Process aProcess = Runtime.getRuntime().exec(string);

            // These two thread shall stop by themself when the process end
            Thread pipeThread = new Thread(new StreamGobber(aProcess.getInputStream()));
            Thread errorThread = new Thread(new StreamGobber(aProcess.getErrorStream()));
            
            pipeThread.start();
            errorThread.start();
            
            aProcess.waitFor();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException ie) {
            ie.printStackTrace();
        }
    }
}

//Replace the following thread with your intends reader
class StreamGobber implements Runnable {

    private InputStream Pipe;

    public StreamGobber(InputStream pipe) {
        if(pipe == null) {
            throw new NullPointerException("bad pipe");
        }
        Pipe = pipe;
    }

    public void run() {
        try {
            byte buffer[] = new byte[2048];

            int read = Pipe.read(buffer);
            while(read >= 0) {
                System.out.write(buffer, 0, read);

                read = Pipe.read(buffer);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(Pipe != null) {
                try {
                    Pipe.close();
                } catch (IOException e) {
                }
            }
        }
    }
}

JavaScript

JavaScript does not have any facilities to interact with the OS. However, host environments can provide this ability.

Works with: JScript
var shell = new ActiveXObject("WScript.Shell");
shell.run("cmd /c dir & pause");
Works with: Rhino
runCommand("cmd", "/c", "dir", "d:\\");
print("===");
var options = {
    // can specify arguments here in the options object
    args: ["/c", "dir", "d:\\"],
    // capture stdout to the options.output property
    output: ''
};
runCommand("cmd", options);
print(options.output);

Joy

<

"ls" system.

Julia

The Julia manual has an excellent section on this topic, which is worth a read. The short answer on Linux is:

run(`ls`)
Output:
$ ls
bitmap_bresenham_line.jl   completed                  single_link_list_collection.jl
color_quantization_in.png  execute_system_command.jl  single_link_list_insert.jl
color_quantization.jl      README.md                  support
$ julia execute_system_command.jl
bitmap_bresenham_line.jl   completed                  single_link_list_collection.jl
color_quantization_in.png  execute_system_command.jl  single_link_list_insert.jl
color_quantization.jl      README.md                  support

K

Execute "ls"

    \ls

Execute "ls" and capture the output in the variable "r":

   r: 4:"ls"

Kotlin

// version 1.0.6

import java.util.Scanner

fun main(args: Array<String>) {
    val proc = Runtime.getRuntime().exec("cmd /C dir")  // testing on Windows 10
    Scanner(proc.inputStream).use {
        while (it.hasNextLine()) println(it.nextLine())
    }
}

Lang5

For one-word commands:

'ls system

For multi-word commands:

"ls -a" system

Lasso

local(
	path	= file_forceroot,
	ls	= sys_process('/bin/ls', (:'-l', #path)),
	lswait	= #ls -> wait
)
'<pre>'
#ls -> read
'</pre>'
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

LFE

In the LFE REPL:

> (os:cmd "ls -alrt")

That will display output on a single line, with literal newlines.

For pretty output, compose with io:format:

> (io:format (os:cmd "ls -alrt"))

Liberty BASIC

 drive1$ = left$(Drives$,1)
run "cmd.exe /";drive1$;" dir & pause"

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:

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";
}

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.

Lingo

Library: Shell Xtra
sx = xtra("Shell").new()
if the platform contains "win" then
  put sx.shell_cmd("dir")
else
  put sx.shell_cmd("ls")
end if

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):

LIST

Works with: UCB Logo

The lines of output of the SHELL command are returned as a list.

print first butfirst shell [ls -a]   ; ..

Logtalk

Using the standard library:

os::shell('ls -a').

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

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


M4

syscmd(ifdef(`__windows__',`dir',`ls'))

Make

make can use system command in either definition of variables or in the targets

in definition

contents=$(shell cat foo)
curdir=`pwd`

in target

mytarget:
   cat foo | grep mytext

Maple

ssystem("dir");

Mathematica / Wolfram Language

Run["ls"]

MATLAB

To execute system commands in MATLAB, use the "system" keyword.

Sample Usage:

>> system('PAUSE')

Press any key to continue . . . 
 

ans =

     0

Maxima

system("dir > list.txt")$

MAXScript

dosCommand "pause"

Mercury

:- 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).

min

Works with: min version 0.19.3
!dir

Modula-2

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.

Modula-3

This code requires the UNSAFE keyword because M3toC deals with C strings (which are pointers), and are implemented in Modula-3 as UNTRACED, meaning they are not garbage collected, which is why the code calls FreeCopiedS().

Also note the EVAL keyword, which ignores the return value of a function.

UNSAFE MODULE Exec EXPORTS Main;

IMPORT Unix, M3toC;

VAR command := M3toC.CopyTtoS("ls");

BEGIN
  EVAL Unix.system(command);
  M3toC.FreeCopiedS(command);
END Exec.

MUMPS

ANSI MUMPS doesn't allow access to the operating system except possibly through the View command and $View function, both of which are implementation specific. Intersystems' Caché does allow you to create processes with the $ZF function, and if the permissions for the Caché process allow it you can perform operating system commands.

In Caché on OpenVMS in an FILES-11 filesystem ODS-5 mode this could work:

Set X=$ZF(-1,"DIR")

In GT.M on OpenVMS, the following will work:

ZSY "DIR"

GT.M on UNIX is the same:

ZSY "ls"

Note: $ZF in GT.M is Unicode version of $F[ind].

Nanoquery

shell("ls")

NetRexx

Translation of: Java
/* NetRexx */
options replace format comments java crossref symbols binary

import java.util.Scanner

runSample(arg)
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
  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

NewLISP

(exec "ls")

Nim

import osproc

let exitCode = execCmd "ls"
let (output, exitCode2) = execCmdEx "ls"

Objective-C

Works with: GCC


NSTask runs an external process with explicit path and arguments.

void runls()
{
    [[NSTask launchedTaskWithLaunchPath:@"/bin/ls"
        arguments:@[]] waitUntilExit];
}

If you need to run a system command, invoke the shell:

void runSystemCommand(NSString *cmd)
{
    [[NSTask launchedTaskWithLaunchPath:@"/bin/sh"
        arguments:@[@"-c", cmd]]
        waitUntilExit];
}

Complete usage example:

Works with: Cocoa


Works with: GNUstep
#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;
}

Or use the C method above.

OCaml

Just run the command:

Sys.command "ls"

To capture the output of the command:

#load "unix.cma"

let syscall cmd =
  let ic, oc = Unix.open_process cmd in
  let buf = Buffer.create 16 in
  (try
     while true do
       Buffer.add_channel buf ic 1
     done
   with End_of_file -> ());
  let _ = Unix.close_process (ic, oc) in
  (Buffer.contents buf)

let listing = syscall "ls" ;;


a more complete version which also returns the contents from stderr, and checks the exit-status, and where the environment can be specified:

let check_exit_status = function
  | Unix.WEXITED 0 -> ()
  | Unix.WEXITED r -> Printf.eprintf "warning: the process terminated with exit code (%d)\n%!" r
  | Unix.WSIGNALED n -> Printf.eprintf "warning: the process was killed by a signal (number: %d)\n%!" n
  | Unix.WSTOPPED n -> Printf.eprintf "warning: the process was stopped by a signal (number: %d)\n%!" n
;;

let syscall ?(env=[| |]) cmd =
  let ic, oc, ec = Unix.open_process_full cmd env in
  let buf1 = Buffer.create 96
  and buf2 = Buffer.create 48 in
  (try
     while true do Buffer.add_channel buf1 ic 1 done
   with End_of_file -> ());
  (try
     while true do Buffer.add_channel buf2 ec 1 done
   with End_of_file -> ());
  let exit_status = Unix.close_process_full (ic, oc, ec) in
  check_exit_status exit_status;
  (Buffer.contents buf1,
   Buffer.contents buf2)
val syscall : ?env:string array -> string -> string * string

Octave

system("ls");

Oforth

System cmd("pause")

Oz

{OS.system "ls" _}

A more sophisticated example can be found here.

PARI/GP

system("ls")

Pascal

Works with: Free_Pascal
Library: SysUtils
Program ExecuteSystemCommand;

uses
  SysUtils;
begin
  ExecuteProcess('/bin/ls', '-alh');
end.

PDP-11 Assembly

PDP-11 running Unix

; 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

So, call with, for example:

mov  #cmd_ls,r1		; => "ls" command string
jsr  pc,CLIsystem
...
.cmd_ls	EQUS "ls",0

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

See also: http://perldoc.perl.org/perlipc.html#Using-open()-for-IPC http://perldoc.perl.org/IPC/Open3.html

Phix

without js
string cmd = iff(platform()=WINDOWS?"dir":"ls")
system(cmd)
integer res = system_exec("pause",4)

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.

PHP

The first line execute the command and the second line display the output:

@exec($command,$output);
echo nl2br($output);

Note:The '@' is here to prevent error messages to be displayed, 'nl2br' translate '\n' chars to 'br' in HTML.

Other:

$results = `ls`;
# runs command and returns its STDOUT as a string

system("ls");
# runs command and returns its exit status; its STDOUT gets output to our STDOUT

echo `ls`;
# the same, but with back quotes

passthru("ls");
# like system() but binary-safe

See also: proc_open()

PicoLisp

(call "ls")

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");
}

Plain English

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.

Pop11

The sysobey function runs commands using a shell:

sysobey('ls');

PowerShell

Since PowerShell is a shell, running commands is the default operation.

dir
ls
Get-ChildItem

are all equivalent (the first two are aliases for the third) but they are PowerShell-native commands. If one really needs to execute dir (which is no program but rather a built-in command in cmd.exe) this can be achieved by

cmd /c dir

Prolog

Works with: SWI Prolog
Works with: GNU Prolog
shell('ls').

PureBasic

ImportC "msvcrt.lib"
  system(str.p-ascii)
EndImport

If OpenConsole()
  system("dir & pause")
  
  Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
  Input()
  CloseConsole()
EndIf

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.

or

Works with: Python version 2.7 (and above)
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+

or

Works with: Python version 2.4 (and above)
from subprocess import PIPE, Popen, STDOUT
p = Popen('ls', stdout=PIPE, stderr=STDOUT)
print p.communicate()[0]

Note: The latter is the preferred method for calling external processes, although cumbersome, it gives you finer control over the process.

or

Works with: Python version 2.2 (and above)
import commands
stat, out = commands.getstatusoutput('ls')
if not stat:
    print out

Quackery

Translation of: Python
$ \
import os
exit_code = os.system('ls') 
\ python
Output:
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

R

system("ls")
output=system("ls",intern=TRUE)

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")

Raku

(formerly Perl 6)

run "ls" orelse .die; # output to stdout

my @ls = qx/ls/;    # output to variable

my $cmd = 'ls';
@ls = qqx/$cmd/;  # same thing with interpolation

Raven

Back tick string is auto executed:

`ls -la` as listing

Or specifically on any string:

'ls -la' shell as listing

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"

Red

call/show %pause        ;The /show refinement forces the display of system's shell window (Windows only).
call/show %dir
call/show %notepad.exe

REXX

Since REXX is a shell scripting language, it's easy to execute commands:

"dir /a:d"

Ring

system("dir")

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}

Run BASIC

print shell$("ls")  ' prints the returned data from the OS
a$ =  shell$("ls")  ' holds returned data in a$

Rust

use std::process::Command;
fn main() {
    let output = Command::new("ls").output().unwrap_or_else(|e| {
        panic!("failed to execute process: {}", e)
    });
    println!("{}", String::from_utf8_lossy(&output.stdout));
}

Scala

import scala.sys.process.Process
Process("ls", Seq("-oa"))!

Scheme

Works with: Guile
Works with: Chicken Scheme
(system "ls")

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:

$ include "seed7_05.s7i";
  include "shell.s7i";

const proc: main is func
  begin
    cmd_sh("ls");
  end func;

SETL

system("ls");

Sidef

# Pipe in read-only mode
%p(ls).open_r.each { |line|
    print line;
};

var str1 = `ls`;         # backtick: returns a string
var str2 = %x(ls);       # ditto, alternative syntax

Sys.system('ls');   # system: executes a command and prints the result
Sys.exec('ls');     # replaces current process with another

Slate

Run a command normally through the shell:

Platform run: 'ls'.

Run a command (this way takes advantage of the 'does not understand' message for the shell object and calls the Platform run: command above with a specific command):

shell ls: '*.slate'.

Smalltalk

Smalltalk system: 'ls'.

SQL PL

Works with: Db2 LUW

In Linux or UNIX:

!ls

Output:

db2 => !ls
adm	  ctrlhamirror	    fm.ip-10-0-0-85.reg  lib64	    profile.env  security64
adsm	  dasfcn	    function		 log	    python32	 spmlog
backup	  db2cshrc	    gskit		 map	    python64	 sqldbdir
bin	  db2dump	    hmonCache		 misc	    rdf		 tmp
bnd	  db2nodes.cfg	    include		 msg	    Readme	 tools
cfg	  db2profile	    infopop		 nodes	    ruby32	 uif
cfgcache  db2systm	    java		 nodes.reg  ruby64	 usercshrc
conv	  doc		    json		 pd	    samples	 userprofile
ctrl	  fm.db2-1.reg	    lib			 php32	    security
ctrlha	  fm.db2-model.reg  lib32		 php64	    security32

In Windows:

!dir

Standard ML

Just run the command:

OS.Process.system "ls"

Stata

Stata has a built-in dir command. However, it's also possible to run arbitrary external programs using the shell or winexec commands.

The command ! (or equivalently shell), opens a Windows console to run the command, while winexec does not.

!dir

* print a message and wait
!echo Ars Longa Vita Brevis & pause

* load Excel from Stata
!start excel

* run a Python program (Python must be installed and accessible in the PATH environment variable)
!python preprocessing.py

* load Windows Notepad
winexec notepad

Tcl

puts [exec ls]

This page uses "ls" as the primary example. For what it's worth, Tcl has built-in primitives for retrieving lists of files so one would rarely ever directly exec an ls command.

It is also possible to execute a system command by "open"ing it through a pipe from whence any output of the command can be read at any (later) time. For example:

set io [open "|ls" r]

would execute "ls" and pipe the result into the channel whose name is put in the "io" variable. From there one could receive it either line by line like this:

set nextline [gets $io]

or read the whole shebang in a fell swoop:

set lsoutput [read $io]

If the command is opened "rw", it is even possible to send it user input through the same handle, though care must be taken with buffering in that case.

exec C:/Windows/System32/taskmgr.exe &

Runs the Task Manager on Windows. If running from a Tcl/Tk Gui the [ & ] prevents blocking the Gui.

Toka

needs shell
" ls" system

TUSCRIPT

$$ MODE TUSCRIPT
system=SYSTEM ()
IF (system=="WIN") THEN
EXECUTE "dir"
ELSEIF (system.sw."LIN") THEN
EXECUTE "ls -l"
ENDIF

UNIX Shell

UNIX shells are designed to run system commands as a default operation.

ls

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.

exec ls

Command substitution

One can also capture the command's standard output in a variable.

With Bourne Shell:

output=`ls`

With Korn Shell or any modern shell:

output=$(ls)
  • 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.

output=`expr \`echo hi | wc -c\` - 1`
output=$(expr $(echo hi | wc -c) - 1)

Both forms, `backticks` and $(...), also work inside double-quoted strings. This prevents file name expansion and also prevents word splitting.

echo "Found: `grep 80/tcp /etc/services`"
echo "Found: $(grep 80/tcp /etc/services)"

C Shell

C Shell also runs system commands, and has an exec built-in command, exactly like Bourne Shell.

ls         # run command, return to shell
exec ls    # replace shell with command

`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.

set output=( "`grep 80/ /etc/services`" )
echo "Line 1: $output[1]"
echo "Line 2: $output[2]"

Ursa

decl string<> arg
decl string<> output
decl iodevice iod

append "ls" arg
set iod (ursa.util.process.start arg)
set output (iod.readlines)

for (decl int i) (< i (size output)) (inc i)
        out output<i> endl console
end for

Ursala

The library function, ask, parameterized by a shell descriptor, such as bash, spawns a process that interacts with that shell by feeding it a list of commands, and returns a transcript of the interaction.

Note that the output from the spawned process is captured and returned only, not sent to the standard output stream of the parent.

Here is a self-contained command line application providing a limited replacement for the ls command.

#import std
#import cli

#executable ('parameterized','')

myls = <.file$[contents: --<''>]>@hm+ (ask bash)/0+ -[ls --color=no]-!

The color option is needed to suppress terminal escape sequences.

VBScript

Set objShell = CreateObject("WScript.Shell")
objShell.Run "%comspec% /K dir",3,True

Vedit macro language

system("dir", DOS)

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:

system('cmd /k "dir"')

Visual Basic

Shelling out a sub task in Visual Basic is rather a pain if you need to wait for the task to complete, which is probably the usual case. But it is possible.

Attribute VB_Name = "mdlShellAndWait"
Option Explicit

Private Declare Function OpenProcess Lib "kernel32" _
    (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, _
    ByVal dwProcessId As Long) As Long

Private Declare Function GetExitCodeProcess Lib "kernel32" _
    (ByVal hProcess As Long, lpExitCode As Long) As Long

Private Const STATUS_PENDING = &H103&
Private Const PROCESS_QUERY_INFORMATION = &H400

'
' Little function go get exit code given processId
'
Function ProcessIsRunning( processId as Long ) as Boolean
    Dim exitCode as Long
    Call GetExitCodeProcess(lProcessId, exitCode)
    ProcessIsRunning = (exitCode = STATUS_PENDING)
End Function

' Spawn subprocess and wait for it to complete.
'   I believe that the command in the command line must be an exe or a bat file.
'   Maybe, however, it can reference any file the system knows how to "Open"
'
' commandLine is an executable. 
' expectedDuration - is for poping up a dialog for whatever
' infoText - text for progressDialog dialog

Public Function ShellAndWait( commandLine As String, _
    expectedDuration As Integer ) As Boolean
    
    Dim inst As Long
    Dim startTime As Long
    Dim expirationTime As Long
    Dim pid As Long
    Dim expiresSameDay As Boolean
    
    On Error GoTo HandleError

    'Deal with timeout being reset at Midnight ($hitForBrains VB folks)
    startTime = CLng(Timer)
    expirationTime = startTime + expectedDuration
    expiresSameDay = expirationTime < 86400
    If Not expiresSameDay Then
        expirationTime = expirationTime - 86400
    End If

    inst = Shell(commandLine, vbMinimizedNoFocus)
    
    If inst <> 0 Then
        pid = OpenProcess(PROCESS_QUERY_INFORMATION, False, inst)

        Do While ProcessIsRunning( pid)
            DoEvents
            If Timer > expirationTime And (expiresSameDay Or Timer < startTime) Then
                Exit Do
            End If
        Loop 
        ShellAndWait = True
    Else
        MsgBox ("Couldn't execute command: " & commandLine)
        ShellAndWait = False
    End If
        
    Exit Function
   
HandleError:
    MsgBox ("Couldn't execute command: " & commandLine)
    ShellAndWait = False
End Function

Sub SpawnDir()
   ShellAndWait("dir", 10)
End Sub

Visual Basic .NET

Works with: Visual Basic .NET version 9.0+
Module System_Command

    Sub Main()
        Dim cmd As New Process
        cmd.StartInfo.FileName = "cmd.exe"
        cmd.StartInfo.RedirectStandardInput = True
        cmd.StartInfo.RedirectStandardOutput = True
        cmd.StartInfo.CreateNoWindow = True
        cmd.StartInfo.UseShellExecute = False

        cmd.Start()

        cmd.StandardInput.WriteLine("dir")
        cmd.StandardInput.Flush()
        cmd.StandardInput.Close()

        Console.WriteLine(cmd.StandardOutput.ReadToEnd)
    End Sub

End Module

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)}
}

Wart

system "ls"

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.

/* 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", "")

which we embed in the following Go program and run it.

Library: WrenGo
/* 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()
}

x86 Assembly

Works with: NASM
Works with: Linux

32 bit

; 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

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.

zkl

System.cmd(System.isWindows and "dir" or "ls")

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:

PAUSE 100