Get system command output: Difference between revisions

Added XPL0 example.
(Added XPL0 example.)
 
(47 intermediate revisions by 28 users not shown)
Line 7:
* [[Execute_a_system_command | Execute a system command]]
<br><br>
=={{header|6502 Assembly}}==
{{works with|Commodore 64}}
Uses the system call <code>$FFED</code> which returns the screen dimensions (measured in 8x8 pixel squares).
<syntaxhighlight lang="6502asm">JSR $FFED
;returns screen width in X and screen height in Y
dex ;subtract 1. This is more useful for comparisons.
dey ;subtract 1. This is more useful for comparisons.
stx $20 ;store in zero page ram
sty $21 ;store in zero page ram</syntaxhighlight>
 
 
=={{header|68000 Assembly}}==
{{works with|NEOGEO MVS}}
This program uses the system command that retrieves the current time, which is used to seed a random number generator. All labels are either routines, macros, or memory locations as appropriate. Code is called during the game's vBlank routine.
<syntaxhighlight lang="68000devpac">doRNG:
;run this during vblank for best results.
JSR SYS_READ_CALENDAR
;gets the calendar.
;MAME uses your computer's time for this.
MOVE.L BIOS_HOUR,D0 ;D0 = HHMMSS00
LSR.L #8,D0 ;shift out the zeroes.
MOVE.L frame_timer,D1 ;this value is incremented by 1 every vBlank (i.e. just before this procedure is run)
NOT.L D1 ;flip all the bits of D1
MULS D1,D0
MULU D1,D0
MOVE.L JOYPAD1,D1 ;get the most recent button presses.
CloneByte D1 ;copy this byte to all 4 bytes of D1
EOR.L D1,D0
MOVE.L RNGout_32,D2 ;look at last time's results.
AND.B #1,D2 ;check if it's odd or even
BNE SwapRNGifEven
SWAP D0 ;if even, swap the low and high words of D0
SwapRNGifEven:
MOVE.L D0,RNGout_32
rts</syntaxhighlight>
 
The following macro is used in the above routine:
<syntaxhighlight lang="68000devpac"> macro CloneByte 1
;\1 must be a data register.
;copies the lowest byte to all 4 bytes.
move.b \1,-(SP)
LSL.L #8,\1
move.b (SP)+,\1
pushWord \1
SWAP \1
popWord \1
endm</syntaxhighlight>
 
=={{header|Ada}}==
{{works with|GNAT}}
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO; use Ada.Text_IO;
with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
with GNAT.Expect; use GNAT.Expect;
Line 48 ⟶ 95:
end loop;
 
end System_Command;</langsyntaxhighlight>
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">o_("-- ", sshell().plan("expr", "8", "*", "9").link.b_dump('\n'), " --\n");</langsyntaxhighlight>
{{Out}}
<pre>-- 72 --</pre>
 
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="amazing hopper">
/* JAMBO language - a flavour of Hopper */
#include <jambo.h>
Main
sys = `cat jm/sys1.jambo`
Set( sys ) Prnl
End
</syntaxhighlight>
{{out}}
<pre>
$ hopper jm/sys1.jambo
#include <jambo.h>
Main
sys = `cat jm/sys1.jambo`
Set( sys ) Prnl
End
$
</pre>
 
=={{header|Applesoft BASIC}}==
A small machine language program is POKEd into memory starting at address P. The address of the program P is POKEd into the 54 and 55 zero page locations. CALL 1002 connects output to the program. The system command CATALOG is run, and all output is written to memory starting at address A. PR#0 reconnects output back to the screen. Variables are carefully declared before the first string in the array S$(0) is assigned. The most recent address of S$(0) is used to assign pointers and lengths to the array of strings. S$(C) is the last string in the array.
<syntaxhighlight lang="qbasic"> 100 HIMEM: 24576
110 LET A = 24576
120 LET P = 768
130 DEF FN P(A) = PEEK (A) + PEEK (A + 1) * 256
140 DEF FN H(A) = INT (A / 256)
150 DEF FN L(A) = A - FN H(A) * 256
160 POKE P + 00,073: REM EOR
170 POKE P + 01,128: REM #$80
180 POKE P + 02,141: REM STA
190 POKE P + 03, FN L(A)
200 POKE P + 04, FN H(A)
210 POKE P + 05,073: REM EOR
220 POKE P + 06,128: REM #$80
230 POKE P + 07,238: REM INC
240 POKE P + 08, FN L(P + 3)
250 POKE P + 09, FN H(P + 3)
260 POKE P + 10,208: REM BNE
270 POKE P + 11,3
280 POKE P + 12,238: REM INC
290 POKE P + 13, FN L(P + 4)
300 POKE P + 14, FN H(P + 4)
310 POKE P + 15,096: REM RTS
320 POKE 54, FN L(P)
330 POKE 55, FN H(P)
340 CALL 1002
350 PRINT CHR$ (4)"CATALOG"
360 PRINT CHR$ (4)"PR#0"
370 LET C = - 1
380 LET I = 0
390 LET S = 0
400 LET E = FN P(P + 3)
410 DIM S$(54)
420 LET S$(0) = ""
430 POKE 236, PEEK (131)
440 POKE 237, PEEK (132)
450 LET S = FN P(236)
460 FOR I = A TO E STEP 255
470 LET C = C + 1
480 POKE S + C * 3,255
490 IF E - I < 255 THEN POKE S + C * 3,E - I
500 POKE S + C * 3 + 1, FN L(I)
510 POKE S + C * 3 + 2, FN H(I)
520 PRINT S$(C);
530 NEXT </syntaxhighlight>
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">print split.lines execute "ls"</syntaxhighlight>
 
{{out}}
 
<pre>LICENSE README.md bin build.nims config.nims docs examples src tests tools version</pre>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
BEGIN {
 
Line 94 ⟶ 216:
close(command)
return ship
}</langsyntaxhighlight>
 
=={{header|BaConBASIC}}==
==={{header|BaCon}}===
<lang freebasic>' Get system command
<syntaxhighlight lang="freebasic">' Get system command
result$ = EXEC$("fortune")
PRINT CHOP$(result$)
PRINT "First word: " & TOKEN$(result$, 1)</langsyntaxhighlight>
 
{{out}}
Line 110 ⟶ 233:
 
=={{header|Batch File}}==
<langsyntaxhighlight lang="dos">
@echo off
setlocal enabledelayedexpansion
Line 136 ⟶ 259:
 
pause>nul
</syntaxhighlight>
</lang>
 
=={{header|Bracmat}}==
<syntaxhighlight lang="bracmat">(system=
.sys$(str$(!arg " > temp"))&get$(temp,STR)
);</syntaxhighlight>
Example:
<syntaxhighlight lang="bracmat">system$ls</syntaxhighlight>
'''Output'''
<pre>Changelog
LICENSE
Linux
Python-module
README.md
Windows
doc
epoc
howto.md
java-JNI
lex.bra
macOS
pr-xml-utf-8.xml
project.bra
safe
src
temp
uni.bra
valid.bra
web</pre>
 
=={{header|C}}==
<syntaxhighlight lang="c">
<lang C>
#include <stdio.h>
#include <stdlib.h>
Line 176 ⟶ 327:
return 0;
}
</syntaxhighlight>
</lang>
 
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">using System;
 
namespace GetSystemCommandOutput {
class Program {
static void Main(string[] args) {
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/c echo Hello World";
startInfo.RedirectStandardOutput = true;
startInfo.UseShellExecute = false;
process.StartInfo = startInfo;
process.Start();
 
string output = process.StandardOutput.ReadToEnd();
Console.WriteLine("Output is {0}", output);
}
}
}</syntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <fstream>
#include <iostream>
 
Line 196 ⟶ 369:
int main() {
std::cout << execute("whoami") << '\n';
}</langsyntaxhighlight>
 
===Boost alternative===
=={{header|C#|C sharp}}==
{{libheader|Boost}}
<lang csharp>using System;
<syntaxhighlight lang="cpp">#include <iostream>
#include <string>
#include <vector>
#include <boost/process.hpp>
 
// Returns a vector containing names of files in the specified directory
namespace GetSystemCommandOutput {
// by capturing the output of the "ls" command, which is specific to
class Program {
// Unix-like operating systems.
static void Main(string[] args) {
// Obviously there are better ways of listing files in a directory; this
System.Diagnostics.Process process = new System.Diagnostics.Process();
// is just an example showing how to use boost::process.
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
std::vector<std::string> list_files(const std::string& directory) {
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
namespace bp = boost::process;
startInfo.FileName = "cmd.exe";
bp::ipstream input;
startInfo.Arguments = "/c echo Hello World";
bp::child process("/bin/ls", directory, bp::std_out > input);
startInfo.RedirectStandardOutput = true;
std::vector<std::string> files;
startInfo.UseShellExecute = false;
std::string file;
process.StartInfo = startInfo;
while (getline(input, file))
process.Start();
files.push_back(file);
process.wait();
if (process.exit_code() != 0)
throw std::runtime_error("Process did not complete successfully.");
return files;
}
 
int main(int argc, char** argv) {
string output = process.StandardOutput.ReadToEnd();
try {
Console.WriteLine("Output is {0}", output);
for (auto file : list_files(argc > 1 ? argv[1] : "."))
}
std::cout << file << '\n';
} catch (const std::exception& ex) {
std::cerr << "Error: " << ex.what() << '\n';
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}</lang>
}</syntaxhighlight>
 
=={{header|Clojure}}==
sh returns a map of exit code, stdout, and stderr from the command:
<langsyntaxhighlight lang="clojure">(use '[clojure.java.shell :only [sh]])
(sh "echo" "Hello")</langsyntaxhighlight>
 
{{out}}
Line 230 ⟶ 418:
=={{header|Common Lisp}}==
{{libheader|trivial-shell}}
<langsyntaxhighlight lang="lisp">(trivial-shell:shell-command "uname -imp")</langsyntaxhighlight>
 
{{out}}
Line 242 ⟶ 430:
the :output keyword. We can then read from the stream:
 
<langsyntaxhighlight lang="lisp">(defparameter *my-proc*
(sb-ext:run-program "mplayer" (list "/path/to/groovy/tune")
:search t :output :stream :wait nil))
(read-line (sb-ext:process-output *my-proc*) nil)</langsyntaxhighlight>
 
{{libheader|uiop}}
A bit more general, using [https://github.com/fare/asdf uiop] and grabbing output as a string:
<langsyntaxhighlight lang="lisp">(uiop:run-program '("ls" "-l" "-a") :output :string)</langsyntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight Dlang="d">import std.process;
import std.stdio;
 
Line 263 ⟶ 451:
writeln("Failed to execute command, status=", cmd.status);
}
}</langsyntaxhighlight>
 
{{out}}
<pre>Output: hello</pre>
 
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">
// System Command Output. Nigel Galloway: October 6th., 2020
let n=new System.Diagnostics.Process(StartInfo=System.Diagnostics.ProcessStartInfo(RedirectStandardOutput=true,RedirectStandardError=true,UseShellExecute=false,
FileName= @"C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\Common7\IDE\CommonExtensions\Microsoft\FSharp\fsc.exe",Arguments="--help"))
n.Start()
printfn "%s" ((n.StandardOutput).ReadToEnd())
n.Close()
</syntaxhighlight>
{{out}}
<pre style="height:64ex;overflow:scroll">
Microsoft (R) F# Compiler version 10.8.0.0 for F# 4.7
Copyright (c) Microsoft Corporation. All Rights Reserved.
 
 
- OUTPUT FILES -
--out:<file> Name of the output file (Short form:
-o)
--target:exe Build a console executable
--target:winexe Build a Windows executable
--target:library Build a library (Short form: -a)
--target:module Build a module that can be added to
another assembly
--delaysign[+|-] Delay-sign the assembly using only
the public portion of the strong
name key
--publicsign[+|-] Public-sign the assembly using only
the public portion of the strong
name key, and mark the assembly as
signed
--doc:<file> Write the xmldoc of the assembly to
the given file
--keyfile:<file> Specify a strong name key file
--keycontainer:<string> Specify a strong name key container
--platform:<string> Limit which platforms this code can
run on: x86, Itanium, x64,
anycpu32bitpreferred, or anycpu. The
default is anycpu.
--nooptimizationdata Only include optimization
information essential for
implementing inlined constructs.
Inhibits cross-module inlining but
improves binary compatibility.
--nointerfacedata Don't add a resource to the
generated assembly containing
F#-specific metadata
--sig:<file> Print the inferred interface of the
assembly to a file
--nocopyfsharpcore Don't copy FSharp.Core.dll along the
produced binaries
 
 
- INPUT FILES -
--reference:<file> Reference an assembly (Short form:
-r)
--compilertool:<file> Reference an assembly or directory
containing a design time tool (Short
form: -t)
 
 
- RESOURCES -
--win32res:<file> Specify a Win32 resource file (.res)
--win32manifest:<file> Specify a Win32 manifest file
--nowin32manifest Do not include the default Win32
manifest
--resource:<resinfo> Embed the specified managed resource
--linkresource:<resinfo> Link the specified resource to this
assembly where the resinfo format is
<file>[,<string
name>[,public|private]]
 
 
- CODE GENERATION -
--debug[+|-] Emit debug information (Short form:
-g)
--debug:{full|pdbonly|portable|embedded} Specify debugging type: full,
portable, embedded, pdbonly. ('full'
is the default if no debuggging type
specified and enables attaching a
debugger to a running program,
'portable' is a cross-platform
format, 'embedded' is a
cross-platform format embedded into
the output file).
--embed[+|-] Embed all source files in the
portable PDB file
--embed:<file;...> Embed specific source files in the
portable PDB file
--sourcelink:<file> Source link information file to
embed in the portable PDB file
--optimize[+|-] Enable optimizations (Short form:
-O)
--tailcalls[+|-] Enable or disable tailcalls
--deterministic[+|-] Produce a deterministic assembly
(including module version GUID and
timestamp)
--pathmap:<path=sourcePath;...> Maps physical paths to source path
names output by the compiler
--crossoptimize[+|-] Enable or disable cross-module
optimizations
 
 
- ERRORS AND WARNINGS -
--warnaserror[+|-] Report all warnings as errors
--warnaserror[+|-]:<warn;...> Report specific warnings as errors
--warn:<n> Set a warning level (0-5)
--nowarn:<warn;...> Disable specific warning messages
--warnon:<warn;...> Enable specific warnings that may be
off by default
--consolecolors[+|-] Output warning and error messages in
color
 
 
- LANGUAGE -
--langversion:{?|version|latest|preview} Display the allowed values for
language version, specify language
version such as 'latest' or
'preview'
--checked[+|-] Generate overflow checks
--define:<string> Define conditional compilation
symbols (Short form: -d)
--mlcompatibility Ignore ML compatibility warnings
 
 
- MISCELLANEOUS -
--nologo Suppress compiler copyright message
--help Display this usage message (Short
form: -?)
--@<file> Read response file for more options
 
 
- ADVANCED -
--codepage:<n> Specify the codepage used to read
source files
--utf8output Output messages in UTF-8 encoding
--preferreduilang:<string> Specify the preferred output
language culture name (e.g. es-ES,
ja-JP)
--fullpaths Output messages with fully qualified
paths
--lib:<dir;...> Specify a directory for the include
path which is used to resolve source
files and assemblies (Short form:
-I)
--simpleresolution Resolve assembly references using
directory-based rules rather than
MSBuild resolution
--targetprofile:<string> Specify target framework profile of
this assembly. Valid values are
mscorlib, netcore or netstandard.
Default - mscorlib
--baseaddress:<address> Base address for the library to be
built
--checksumalgorithm:{SHA1|SHA256} Specify algorithm for calculating
source file checksum stored in PDB.
Supported values are: SHA1 or SHA256
(default)
--noframework Do not reference the default CLI
assemblies by default
--standalone Statically link the F# library and
all referenced DLLs that depend on
it into the assembly being generated
--staticlink:<file> Statically link the given assembly
and all referenced DLLs that depend
on this assembly. Use an assembly
name e.g. mylib, not a DLL name.
--pdb:<string> Name the output debug file
--highentropyva[+|-] Enable high-entropy ASLR
--subsystemversion:<string> Specify subsystem version of this
assembly
--quotations-debug[+|-] Emit debug information in quotations
</pre>
=={{header|Factor}}==
<code>with-process-reader</code> is a combinator that encapsulates reading the output of a system command. It also throws an error along with the appropriate exit status in the event of failure.
<langsyntaxhighlight lang="factor">USING: io.encodings.utf8 io.launcher ;
"echo hello" utf8 [ contents ] with-process-reader .</langsyntaxhighlight>
{{out}}
<pre>
"hello\n"
</pre>
 
=={{header|Forth}}==
Using Gforth 0.7.9
<syntaxhighlight lang="forth">s" ps " system \ Output only
\ read via pipe into buffer
create buffer 266 allot
s" ps " r/o open-pipe throw
dup buffer swap 256 swap
read-file throw
swap close-pipe throw drop
buffer swap type \ output is the same like above
</syntaxhighlight>
{{out}}
<pre>
PID TTY TIME CMD
17067 pts/5 00:00:00 bash
27298 pts/5 00:14:00 gforth
32815 pts/5 00:00:00 sh
32816 pts/5 00:00:00 ps
</pre>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
'capture the output of the 'dir' command and print it to a text file
Line 293 ⟶ 674:
Close #2
Close #1
End</langsyntaxhighlight>
 
 
=={{header|FutureBasic}}==
Simple system commands can be run in FB's open "UNIX" function. However, more common are functions such as this example which uses a notification observer to watch as data is downloaded in the background. The command in this example returns the mdls man page.
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
 
local fn ObserverOne( ref as NotificationRef )
FileHandleRef fh = fn NotificationObject( ref )
CFDataRef dta = fn FileHandleAvailableData( fh )
if ( fn DataLength( dta ) > 0 )
CFStringRef string = fn StringWithData( dta, NSUTF8StringEncoding )
NSLog( @"%@", string )
FileHandleWaitForDataInBackgroundAndNotify( fh )
else
NotificationCenterRemoveObserver( @fn ObserverOne, NSFileHandleDataAvailableNotification )
end if
end fn
 
local fn RunCommand( cmdStr as CFStringRef )
TaskRef task = fn TaskInit
TaskSetExecutableURL( task, fn URLFileURLWithPath( @"/bin/sh" ) )
CFArrayRef arguments = fn ArrayWithObjects( @"-c", cmdStr, NULL )
TaskSetArguments( task, arguments )
PipeRef p = fn PipeInit
TaskSetStandardOutput( task, p )
FileHandleRef fh = fn PipeFileHandleForReading( p )
NotificationCenterAddObserver( @fn ObserverOne, NSFileHandleDataAvailableNotification, (FileHandleRef)fh )
fn TaskLaunch( task, NULL )
FileHandleWaitForDataInBackgroundAndNotify( fh )
end fn
 
fn RunCommand( @"man mdls | col -b" )
 
HandleEvents
</syntaxhighlight>
 
{{out}}
<pre>
 
MDLS(1) BSD General Commands Manual MDLS(1)
 
NAME
mdls -- lists the metadata attributes for the specified file
 
SYNOPSIS
mdls [-name attributeName] [-raw [-nullMarker markerString]] file ...
 
DESCRIPTION
The mdls command prints the values of all the metadata attributes associ-
ated with the files provided as an argument.
 
The following options are available:
 
-name Print only the matching metadata attribute value. Can be
used multiple times.
 
-raw Print raw attribute data in the order that was requested.
Fields will be separated with a ASCII NUL character, suit-
able for piping to xargs(1) -0.
 
-nullMarker Sets a marker string to be used when a requested attribute
is null. Only used in -raw mode. Default is "(null)".
 
SEE ALSO
mdfind(1), mdutil(1) xargs(1)
 
Mac OS X June 3, 2004 Mac OS X
</pre>
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=d595094b5bc9c3abb17808b2b00938f9 Click this link to run this code]'''
<langsyntaxhighlight lang="gambas">Public Sub Main()
Dim sStore As String
 
Line 303 ⟶ 754:
Print sStore
 
End</langsyntaxhighlight>
 
Output:
Line 324 ⟶ 775:
 
=={{header|Genie}}==
<langsyntaxhighlight lang="genie">[indent=4]
/*
Get system command output, in Genie
Line 342 ⟶ 793:
print standard_output
except e : SpawnError
stderr.printf("%s\n", e.message)</langsyntaxhighlight>
 
{{out}}
Line 353 ⟶ 804:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 367 ⟶ 818:
}
fmt.Print(string(output))
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
Line 373 ⟶ 824:
{{libheader|process}}
 
<langsyntaxhighlight lang="haskell">#!/usr/bin/env stack
-- stack --resolver lts-8.15 --install-ghc runghc --package process
 
Line 384 ⟶ 835:
-- print each line in reverse
mapM_ (putStrLn . reverse) results</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight lang="unicon">#
# piped.icn, Get system command output
#
Line 409 ⟶ 860:
 
close(p)
end</langsyntaxhighlight>
 
{{out}}
Line 415 ⟶ 866:
piped.u
</pre>
 
=={{header|IS-BASIC}}==
<syntaxhighlight lang="is-basic">100 OPEN #1:"dirinfo.txt" ACCESS OUTPUT
110 SET DEFAULT CHANNEL 1
120 EXT "dir"
130 CLOSE #1
140 SET DEFAULT CHANNEL 0</syntaxhighlight>
 
=={{header|J}}==
Line 420 ⟶ 878:
We will box the result of uname -imp on a linux system, to show that we have captured the command output in J:
 
<langsyntaxhighlight Jlang="j"> require 'task'
<shell 'uname -imp'
┌─────────────────────┐
│x86_64 x86_64 x86_64 │
└─────────────────────┘</langsyntaxhighlight>
 
Caution: I have sometimes seen some versions of linux refuse to execute subshells after a few hundred thousand shell commands (the exec system call fails). I've not found any satisfying documentation on why this happens, but I strongly suspect kernel memory fragmentation (the examples where this happened were also using a lot of memory to accumulate results and it happened much more frequently anon machines with little memory than on machines with more memory). Exiting J and starting a new process has cleared it up when it has happened. AnywaysWhen that becomes an issue, I usually prefer to do that kindsubshell ofresult processingcapture before J starts, just to be safe.
 
(I've seen other problems on windows and osx - I am only singling out linux here because it is the most convenient for command line and system command use.)
Line 432 ⟶ 890:
=={{header|Java}}==
{{works with|Java|7}}
<langsyntaxhighlight lang="java">import java.io.*;
import java.util.*;
 
Line 450 ⟶ 908:
}
}
}</langsyntaxhighlight>
 
Output:
Line 473 ⟶ 931:
 
=={{header|Jsish}}==
<langsyntaxhighlight lang="javascript">var commandOutput = exec('ls -gocart', { retAll:true });
puts(commandOutput.data);</langsyntaxhighlight>
 
The jsish ''exec'' command (like many jsish commands) accepts an optional option object, details available with interactive help:
Line 502 ⟶ 960:
The fifth element of the sample capture (''ls -gocart'') being:
<pre># commandOutput.data.split('\n')[4];
-rw-rw-r--. 1 155 Feb 8 07:52 JSON.jsi</pre>
 
=={{header|Julia}}==
Line 508 ⟶ 966:
 
In a single string:
<langsyntaxhighlight lang="julia">ls = readstring(`ls`)</langsyntaxhighlight>
 
In multiple lines:
<langsyntaxhighlight lang="julia">ll = readlines(`ls -l`)</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6
 
import java.util.Scanner
Line 524 ⟶ 982:
println(sc.nextLine())
sc.close()
}</langsyntaxhighlight>
 
{{out}}
Line 530 ⟶ 988:
Active code page: 850
</pre>
 
=={{header|LIL}}==
The library from lil.c does not include a system command, but main.c for the lil shell does.
 
<syntaxhighlight lang="tcl">set rc [system ls -go]</syntaxhighlight>
 
{{out}}
<pre>prompt$ ./lil
Little Interpreted Language Interactive Shell
# set rc [system ls -go]
total 1076
-rw-rw-r--. 1 729 Jan 14 2019 and.lil
drwxrwxr-x. 3 4096 Jan 14 2019 atom
-rw-rw-r--. 1 798 Jan 14 2019 call.lil
-rw-rw-r--. 1 3079 Aug 4 22:44 catcher.lil
drwxrwxr-x. 2 4096 Jan 14 2019 dll
-rw-rw-r--. 1 593 Jan 14 2019 dollar.lil
-rw-rw-r--. 1 697 Jan 14 2019 downeval.lil
-rw-rw-r--. 1 904 Jan 14 2019 enveval.lil
-rw-rw-r--. 1 1172 Jan 14 2019 expr.lil
-rw-rw-r--. 1 180 Jan 14 2019 fileio.lil
-rw-rw-r--. 1 427 Jan 14 2019 filter.lil
drwxrwxr-x. 2 4096 Jan 14 2019 fplil
-rw-rw-r--. 1 1369 Jan 14 2019 funcs.lil
-rw-rw-r--. 1 49 Jan 14 2019 hello.lil
-rw-rw-r--. 1 368 Jan 14 2019 jaileval.lil
-rw-rw-r--. 1 214990 Aug 8 03:18 liblil.a
-rw-rw-r--. 1 843 Jan 14 2019 liblil.tgt
-rwxrwxr-x. 1 174216 Aug 8 03:18 lil
-rw-rw-r--. 1 108062 Aug 8 03:18 lil.c
-rw-rw-r--. 1 5963 Jan 14 2019 lil.h
-rw-rw-r--. 1 214000 Aug 8 03:18 lil.o
-rw-rw-r--. 1 108 Jan 14 2019 lil.pro
-rw-rw-r--. 1 1244 Jan 14 2019 lil.tgt
-rw-rw-r--. 1 362 Jan 14 2019 lil.wpj
-rw-rw-r--. 1 666 Jan 14 2019 lists.lil
-rw-rw-r--. 1 469 Jan 14 2019 local.lil
-rw-rw-r--. 1 6082 Jan 14 2019 main.c
-rw-rw-r--. 1 137440 Jul 26 12:29 main.o
-rw-rw-r--. 1 968 Jan 14 2019 Makefile
-rw-rw-r--. 1 455 Jan 14 2019 Makefile.bcc
-rw-rw-r--. 1 1955 Jan 14 2019 mandelbrot.lil
-rw-rw-r--. 1 603 Jan 14 2019 mkmsvc.bat
-rw-rw-r--. 1 699 Jan 14 2019 mlcmt.lil
-rw-rw-r--. 1 1653 Jan 14 2019 oop_animals.lil
-rw-rw-r--. 1 1929 Jan 14 2019 oop.lil
-rw-rw-r--. 1 57495 Jan 14 2019 readme.txt
-rw-rw-r--. 1 811 Jan 14 2019 recfuncdef.lil
-rw-rw-r--. 1 1231 Jan 14 2019 renamefunc.lil
-rw-rw-r--. 1 333 Jan 14 2019 result.lil
-rw-rw-r--. 1 310 Jan 14 2019 return.lil
-rw-rw-r--. 1 1096 Jan 14 2019 robot.lil
-rw-rw-r--. 1 2368 Jan 14 2019 sm.lil
-rw-rw-r--. 1 1187 Jan 14 2019 strings.lil
-rw-rw-r--. 1 813 Jan 14 2019 topeval.lil
-rw-rw-r--. 1 615 Jan 14 2019 trim.lil
-rw-rw-r--. 1 1720 Jan 14 2019 upeval.lil
drwxrwxr-x. 2 4096 Jan 14 2019 vim
-rw-rw-r--. 1 1995 Jan 14 2019 watch.lil
 
# length $rc
2107</pre>
 
=={{header|Lingo}}==
{{libheader|Shell Xtra}}
<langsyntaxhighlight lang="lingo">sx = xtra("Shell").new()
put sx.shell_cmd("cd C:\dev\lsw\lib & dir")
 
Line 545 ⟶ 1,065:
23.06.2016 18:22 <DIR> base64
23.06.2016 18:21 <DIR> base9
<snip>"</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">local output = io.popen("echo Hurrah!")
print(output:read("*all"))</langsyntaxhighlight>
{{out}}
<pre>Hurrah!</pre>
 
=={{header|Mathematica}}==
<lang Mathematica>RunProcess["date"]</lang>
{{out}}
<pre><|"ExitCode" -> 0, "StandardOutput" -> "Wed Oct 4 14:01:01 BST 2017", "StandardError" -> ""|></pre>
 
=={{header|M2000 Interpreter}}==
Make a UTF-16LE txt.out from dir using a new cmd with /U
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckIt {
Dos "cd "+quote$(Dir$) +" & cmd /U /C dir *.txt >txt.out";
Line 573 ⟶ 1,088:
}
Checkit
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">RunProcess["date"]</syntaxhighlight>
{{out}}
<pre><|"ExitCode" -> 0, "StandardOutput" -> "Wed Oct 4 14:01:01 BST 2017", "StandardError" -> ""|></pre>
 
=={{header|Neko}}==
<langsyntaxhighlight ActionScriptlang="actionscript">/* Get system command output, neko */
var process_run = $loader.loadprim("std@process_run", 2);
var process_stdout_read = $loader.loadprim("std@process_stdout_read", 4);
Line 634 ⟶ 1,153:
/* Get the exit status */
var ps = process_exit(proc);
sys_exit(ps);</langsyntaxhighlight>
 
{{out}}
Line 652 ⟶ 1,171:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import osproc
 
# Output string and error code
Line 665 ⟶ 1,184:
 
echo "Output: " & lsStr
</syntaxhighlight>
</lang>
 
=={{header|Objeck}}==
<syntaxhighlight lang="objeck">class Test {
function : Main(args : String[]) ~ Nil {
output := System.Runtime->CommandOutput("ls -l");
each(i : output) {
output[i]->PrintLine();
};
}
}
</syntaxhighlight>
 
=={{header|ooRexx}}==
===version 1===
<langsyntaxhighlight ooRexxlang="oorexx">/* Execute a system command and retrieve its output into a stem. */
trace normal
 
Line 695 ⟶ 1,225:
 
/* Exit with the system command's return code. */
exit ls_rc</langsyntaxhighlight>
===version 2===
<langsyntaxhighlight lang="oorexx">cmd='dir tu*.rex /od'
cmd '| rxqueue'
Say 'Output of "'cmd'"'
Line 704 ⟶ 1,234:
parse pull text
Say text
End </langsyntaxhighlight>
{{out}}
<pre>Output of "dir tu*.rex /od"
Line 718 ⟶ 1,248:
0 Verzeichnis(se), 3.357.933.568 Bytes frei </pre>
===version 3===
<langsyntaxhighlight lang="oorexx">dir='dir.dir'
cmd='dir t*.rex /od'
cmd '>'dir
Line 727 ⟶ 1,257:
Say linein(dir)
End
Call lineout oid</langsyntaxhighlight>
{{out}}
<pre>identical to version 2's output</pre>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">externstr("time/t")</langsyntaxhighlight>
 
=={{Headerheader|Perl}}==
Uses the qx{} construct (which is a synonym for backticks, e.g. `command`) to execute a given command and redirect its output.
A (somewhat contrived*) example, capturing only STDOUT:
<langsyntaxhighlight lang="perl">my @directories = grep { chomp; -d } `ls`;
for (@directories) {
chomp;
...; # Operate on directories
}</langsyntaxhighlight>
* Perl's opendir function should be used in preference to parsing ls--it's safer, faster, and more portable.
 
Perl also honors shell redirections:
<langsyntaxhighlight lang="perl">my $command = shift or die "No command supplied\n";
my @output_and_errors = qx/$command 2>&1/ or die "Couldn't execute command\n";</langsyntaxhighlight>
qx// is implemented internally with the built-in function readpipe, which can be invoked directly as readpipe EXPR (where EXPR is some command) and assigned to scalars or lists just like qx/command/ or `command`.
 
The open command can also be used to open pipes using the -| mode:
<langsyntaxhighlight lang="perl">use autodie;
my $enc = ':encoding(UTF-8)';
my $child_pid = open(my $pipe, "-|$enc", 'ls');
Line 756 ⟶ 1,286:
# Print all files whose names are all lowercase
print if m/[^A-Z]+/;
}</langsyntaxhighlight>
 
=={{header|Perl 6Phix}}==
<!--<syntaxhighlight lang="phix">(notonline)-->
If you don't want to execute it in shell (and you probably don't), then use this:
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- system_exec, file i/o</span>
<lang perl6>say run($command, $arg1, $arg2, :out).out.slurp-rest;</lang>
<span style="color: #008080;">constant</span> <span style="color: #000000;">tmp</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"hostname.txt"</span><span style="color: #0000FF;">,</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;">"hostname"</span><span style="color: #0000FF;">:</span><span style="color: #008000;">"uname -n"</span><span style="color: #0000FF;">)</span>
Unfortunately, it is very long to type, but that is the only way to pass your variables as arguments safely.
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">system_exec</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"%s &gt; %s"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">cmd</span><span style="color: #0000FF;">,</span><span style="color: #000000;">tmp</span><span style="color: #0000FF;">}),</span><span style="color: #000000;">4</span><span style="color: #0000FF;">)</span>
 
<span style="color: #004080;">string</span> <span style="color: #000000;">host</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">trim</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">get_text</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tmp</span><span style="color: #0000FF;">))</span>
You might be tempted to start using shell when you have to pipe something, but even in that case there is no need to do so. See this code:
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">delete_file</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tmp</span><span style="color: #0000FF;">)</span>
<lang perl6>my $p1 = run 'echo', 'Hello, world', :out;
<span style="color: #0000FF;">?</span><span style="color: #000000;">host</span>
my $p2 = run 'cat', '-n', :in($p1.out), :out;
<!--</syntaxhighlight>-->
say $p2.out.slurp-rest;</lang>
See [http://doc.perl6.org/type/Proc docs] for more info.
 
If you really want to run something in shell and you understand potential security problems, then you can use <code>qx//</code> (interpolates environment variables) or <code>qqx//</code> (interpolates normally). See [http://doc.perl6.org/language/quoting the docs for more info].
 
<lang perl6>say qx[dir]</lang>
{{out}}
<pre>
<pre>Find_URI_in_text.p6 History_variables.p6 K-d_tree.pl
"Pete-PC"
Fractran.pl History_variables.pl XML_Input.p6</pre>
</pre>
See also demo\capture_console.exw (needs a bit more work on linux)
 
=={{header|Phixmonti}}==
<syntaxhighlight lang="phixmonti">"hostname.txt" var hname
"hostname > " hname chain cmd
hname "r" fopen
dup fgets print fclose
"del " hname chain cmd</syntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">: (in '(uname "-om") (line T))
-> "aarch64 Android"</langsyntaxhighlight>
 
=={{header|PowerShell}}==
Capture system disk label information as an array of strings:
<syntaxhighlight lang="powershell">
<lang PowerShell>
[string[]]$volume = cmd /c vol
 
$volume
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 793 ⟶ 1,327:
Volume Serial Number is 8C33-162D
</pre>
 
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">If OpenConsole("ls")
rp=RunProgram("ls", "-l", "",#PB_Program_Open|#PB_Program_Read)
While ProgramRunning(rp)
If AvailableProgramOutput(rp)
r$+ReadProgramString(rp)+#LF$
EndIf
Wend
CloseProgram(rp)
PrintN(r$)
Input()
EndIf
</syntaxhighlight>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">>>> import subprocess
>>> returned_text = subprocess.check_output("dir", shell=True, universal_newlines=True)
>>> type(returned_text)
Line 823 ⟶ 1,371:
9 Dir(s) 46,326,947,840 bytes free
 
>>> # Ref: https://docs.python.org/3/library/subprocess.html</langsyntaxhighlight>
 
=={{header|Quackery}}==
 
As a dialogue in the Quackery shell. Execute the system command <code>ls</code> and store the result on the Quackery data stack as a string. Reverse that string and print it.
 
 
<pre>/O> $ /
... import subprocess
... string_to_stack(str(subprocess.check_output('ls'),encoding='utf-8'))
... / python
... reverse echo$
...
 
ykq.kcudeltrut
yrdnus
yp.yrekcauq
ykq.Xsnoisnetxe
ykq.targib
fdp.yrekcauQ fo kooB ehT
fdp.tnirp rof yrekcauQ fo kooB ehT
txt.TSRIF EM DAER
fdp.ecnerefeR kciuQ yrekcauQ
</pre>
 
=={{header|R}}==
<langsyntaxhighlight lang="rsplus">
system("wc -l /etc/passwd /etc/group", intern = TRUE)
</syntaxhighlight>
[1] " 49 /etc/passwd" " 80 /etc/group" " 129 total"
</lang>
{{out}}
<pre>
Line 837 ⟶ 1,408:
We use <code>#lang racket/base</code> to show which module system is in. It would be imported anyway if we use the larger <code>#lang racket</code>.
 
This demonstrates one function: <code>system</system></code>. It is the simplest of a family of commands in the <code>racket/system</code> collection.
 
See [http://docs.racket-lang.org/reference/subprocess.html?q=system#%28def._%28%28lib._racket%2Fsystem..rkt%29._system%29%29 documentation for <code>system</code> and friends].
 
<langsyntaxhighlight lang="racket">#lang racket/base
 
(require racket/system
Line 868 ⟶ 1,439:
(system "echo -n foo; echo bar 1>&2"))))
(values system-rv (get-output-string out-str-port) (get-output-string err-str-port)))
=> (values #t "foo" "bar\n"))</langsyntaxhighlight>
 
{{out}}
Line 883 ⟶ 1,454:
7 tests passed
</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
 
If you don't want to execute it in shell (and you probably don't), then use this:
<syntaxhighlight lang="raku" line>say run($command, $arg1, $arg2, :out).out.slurp;</syntaxhighlight>
 
Unfortunately, it is very long to type, but that is the only way to pass your variables as arguments safely.
 
You might be tempted to start using shell when you have to pipe something, but even in that case there is no need to do so. See this code:
<syntaxhighlight lang="raku" line>my $p1 = run 'echo', 'Hello, world', :out;
my $p2 = run 'cat', '-n', :in($p1.out), :out;
say $p2.out.slurp-rest;</syntaxhighlight>
See [https://docs.raku.org/type/Proc docs] for more info.
 
If you really want to run something in shell and you understand potential security problems, then you can use <code>qx//</code> (interpolates environment variables) or <code>qqx//</code> (interpolates normally). See [https://docs.raku.org/language/quoting the docs for more info].
 
<syntaxhighlight lang="raku" line>say qx[dir]</syntaxhighlight>
{{out}}
<pre>Find_URI_in_text.p6 History_variables.p6 K-d_tree.pl
Fractran.pl History_variables.pl XML_Input.p6</pre>
 
=={{header|REXX}}==
{{works with|Regina REXX}}
<langsyntaxhighlight lang="rexx">/*REXX program executes a system command and displays the results (from an array). */
parse arg xxxCmd /*obtain the (system) command from CL.*/
trace off /*suppress REXX error msgs for fails. */
Line 896 ⟶ 1,488:
say strip(@.#, 'T') /*display one line at a time──►terminal*/
end /*#*/ /* [↑] displays all the output. */
exit 0 /*stick a fork in it, we're all done. */</langsyntaxhighlight>
{{out|output|text=&nbsp; from the executed command &nbsp; (under Windows/XP): &nbsp; &nbsp; <tt> &nbsp; dir &nbsp; g:sub*.2*</tt>}}
<pre>
Line 918 ⟶ 1,510:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
system("dir C:\Ring\doc")
</syntaxhighlight>
</lang>
Output:
<pre>
Line 935 ⟶ 1,527:
2 Dir(s) 949 801 435 136 bytes free
</pre>
 
=={{header|Ruby}}==
Many options, google exec or system or %x. Demonstrating backticks:
<syntaxhighlight lang="ruby">str = `ls`
arr = `ls`.lines</syntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">a$ = shell$("dir") ' Returns the directory info into a$
print a$ ' prints the directory
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
Many options, google exec or system or %x. Demonstrating backticks:
<lang ruby>str = `ls`
arr = `ls`.lines</lang>
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">use std::process::Command;
use std::io::{Write, self};
 
Line 956 ⟶ 1,549:
 
io::stdout().write(&output.stdout);
}</langsyntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">import scala.io.Source
 
val command = "cmd /c echo Time at %DATE% %TIME%"
val p = Runtime.getRuntime.exec(command)
val sc = Source.fromInputStream(p.getInputStream)
println(sc.mkString)</langsyntaxhighlight>
 
=={{header|Sidef}}==
Using backticks:
<langsyntaxhighlight lang="ruby">var output = `ls` # `output` is a string
var lines = `ls`.lines # `lines` is an array</langsyntaxhighlight>
 
Using pipes:
<langsyntaxhighlight lang="ruby">var pipe = %p(ls) # same as: Pipe('ls')
var pipe_h = pipe.open_r # open the pipe for reading
var lines = [] # will store the lines of the output
pipe_h.each { |line| lines << line }</langsyntaxhighlight>
 
=={{header|Stata}}==
Redirect the output to a temporary file, then read its contents into a result macro r(out).
 
<langsyntaxhighlight lang="stata">program shellout, rclass
tempfile f
tempname m
Line 993 ⟶ 1,587:
return local out "`s'"
}
end</langsyntaxhighlight>
 
'''Example:'''
 
<langsyntaxhighlight lang="stata">. shellout dir /b *.dta
. display r(out)
auto.dta
Line 1,004 ⟶ 1,598:
. shellout python -V
. display r(out)
Python 3.6.2</langsyntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight Swiftlang="swift">import Foundation
 
let process = Process()
Line 1,022 ⟶ 1,616:
let output = String.init(data: data, encoding: String.Encoding.utf8)
 
print(output!)</langsyntaxhighlight>
 
=={{header|Standard ML}}==
<syntaxhighlight lang="standard ml">val useOS = fn input =>
let
val text = String.translate (fn #"\"" => "\\\""|n=>str n ) input ;
val shellCommand = " echo " ^ text ^ "| gzip -c " ;
val fname = "/tmp/fConv" ^ (String.extract (Time.toString (Posix.ProcEnv.time()),7,NONE) );
val me = ( Posix.FileSys.mkfifo
(fname,
Posix.FileSys.S.flags [ Posix.FileSys.S.irusr,Posix.FileSys.S.iwusr ]
) ;
Posix.Process.fork ()
) ;
in
if (Option.isSome me) then
let
val fin =BinIO.openIn fname
in
( Posix.Process.sleep (Time.fromReal 0.1) ;
BinIO.inputAll fin before
(BinIO.closeIn fin ; OS.FileSys.remove fname )
)
end
else
( OS.Process.system ( shellCommand ^ " > " ^ fname ^ " 2>&1 " ) ;
Word8Vector.fromList [] before OS.Process.exit OS.Process.success
)
end;
</syntaxhighlight>
call
useOS "This is my text, zip it now" ;
val it =
fromList[0wx1F, 0wx8B, 0wx8, 0wx0, 0wxBE, 0wxCE, 0wx7F, 0wx5E, 0wx0, 0wx3,
...]: BinIO.vector
 
=={{header|Tcl}}==
The <code>exec</code> makes this straight-forward for most commands.
<langsyntaxhighlight lang="tcl">set data [exec ls -l]
puts "read [string length $data] bytes and [llength [split $data \n]] lines"</langsyntaxhighlight>
There are a few exceptions, such as the <tt>DIR</tt> command on Windows, where they need to be run slightly differently due to being system shell builtins rather than executables. In that case, the <code>auto_execok</code> standard library command is used to look up how to run the command (strictly it can be used for any command — it will do path resolution, etc. — but is only necessary for system builtins).
<langsyntaxhighlight lang="tcl">set data [exec {*}[auto_execok DIR]]</langsyntaxhighlight>
By default, Tcl will use the system encoding (as reported by <code>encoding system</code>) to understand the output byte-stream as characters, and will auto-convert all the various types of newline terminators into <tt>U+00000A</tt> characters. Control over this is possible by launching the subprocess as a pipe, configuring the pipe, and then reading the pipe in its entirety.
<langsyntaxhighlight lang="tcl"># This syntax is pretty ugly, alas
set pipe [open |[list ls -l] "r"]
fconfigure $pipe -encoding iso8859-1 -translation lf
set data [read $pipe]
close $pipe</langsyntaxhighlight>
This is usually not necessary except when dealing with binary data output.
 
=={{header|VBScript}}==
This program implements a function that executes a DOS command and returns the output to the caller.
<lang vb>For Each line In ExecCmd("ipconfig /all")
Wscript.Echo line
Next
 
'Execute the given command and return the output in a text array.
Function ExecCmd(cmd)
 
'Execute the command
Dim wso : Set wso = CreateObject("Wscript.Shell")
Dim exec : Set exec = wso.Exec(cmd)
Dim res : res = ""
 
'Read all result text from standard output
Do
res = res & VbLf & exec.StdOut.ReadLine
Loop Until exec.StdOut.AtEndOfStream
 
'Return as a text array
ExecCmd = Split(Mid(res,2),vbLf)
End Function</lang>
 
=={{header|Ursa}}==
This program reads the output of the ifconfig command into the string stream 'output', then writes it to the screen.
<langsyntaxhighlight lang="ursa">> decl iodevice iod
> decl string<> arg
> append "ifconfig" arg
Line 1,102 ⟶ 1,707:
media: autoselect
status: inactive
> </langsyntaxhighlight>
 
=={{header|VBScript}}==
This program implements a function that executes a DOS command and returns the output to the caller.
<syntaxhighlight lang="vb">For Each line In ExecCmd("ipconfig /all")
Wscript.Echo line
Next
 
'Execute the given command and return the output in a text array.
Function ExecCmd(cmd)
 
'Execute the command
Dim wso : Set wso = CreateObject("Wscript.Shell")
Dim exec : Set exec = wso.Exec(cmd)
Dim res : res = ""
 
'Read all result text from standard output
Do
res = res & VbLf & exec.StdOut.ReadLine
Loop Until exec.StdOut.AtEndOfStream
 
'Return as a text array
ExecCmd = Split(Mid(res,2),vbLf)
End Function</syntaxhighlight>
 
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<syntaxhighlight lang="vbnet">Module Module1
 
Sub Main()
Dim proccess As New Process
Dim startInfo As New ProcessStartInfo
 
startInfo.WindowStyle = ProcessWindowStyle.Hidden
startInfo.FileName = "cmd.exe"
startInfo.Arguments = "/c echo Hello World"
startInfo.RedirectStandardOutput = True
startInfo.UseShellExecute = False
 
proccess.StartInfo = startInfo
proccess.Start()
 
Dim output = proccess.StandardOutput.ReadToEnd
Console.WriteLine("Output is {0}", output)
End Sub
 
End Module</syntaxhighlight>
 
=={{header|Wren}}==
Wren CLI doesn't currently expose a way to either execute a system command or to get its output.
 
However, if Wren is embedded in (say) a suitable Go program, then we can ask the latter to do it for us.
 
<syntaxhighlight lang="wren">/* Get_system_command_output.wren */
class Command {
foreign static output(name, param) // the code for this is provided by Go
}
 
System.print(Command.output("ls", "-ls"))</syntaxhighlight>
 
which we embed in the following Go program and run it.
{{libheader|WrenGo}}
<syntaxhighlight lang="go">/* Get_system_command_output.go */
package main
 
import (
wren "github.com/crazyinfin8/WrenGo"
"log"
"os"
"os/exec"
)
 
type any = interface{}
 
func getCommandOutput(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.Stderr = os.Stderr
bytes, err := cmd.Output()
if err != nil {
log.Fatal(err)
}
return string(bytes), nil
}
 
func main() {
vm := wren.NewVM()
fileName := "Get_system_command_output.wren"
methodMap := wren.MethodMap{"static output(_,_)": getCommandOutput}
classMap := wren.ClassMap{"Command": wren.NewClass(nil, nil, methodMap)}
module := wren.NewModule(classMap)
vm.SetModule(fileName, module)
vm.InterpretFile(fileName)
vm.Free()
}</syntaxhighlight>
 
=={{header|XPL0}}==
Use a pipe on the command line to run this. For example: dir | syscmd
<syntaxhighlight lang "XPL0">int C;
repeat C:= ChIn(1);
if C>=^a & C<=^z then \lowercase letters to uppercase
C:= C & ~$20;
ChOut(0, C);
until C = $1A</syntaxhighlight>
 
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">// Rosetta Code problem: https://www.rosettacode.org/wiki/Get_system_command_output
// by Jjuanhdez, 06/2022
 
if peek$("os") = "unix" then
c$ = "ls *"
else //"windows"
c$ = "dir *.*"
fi
 
open("dir_output.txt") for writing as #1
print #1 system$(c$)
close #1</syntaxhighlight>
 
=={{header|zkl}}==
From the REPL on Linux. Runs a command in the shell with stdout redirected to file, then slurps the file. A bit greasy since there isn't a way to find/generate a unique unused file name.
<langsyntaxhighlight lang="zkl">zkl: System.cmd("date >foo.txt")
0 // date return code
zkl: File("foo.txt").read().text
Wed Aug 20 00:28:55 PDT 2014</langsyntaxhighlight>
291

edits