Shell one-liner

From Rosetta Code
Revision as of 03:05, 16 April 2011 by Objeck (talk | contribs)
Task
Shell one-liner
You are encouraged to solve this task according to the task description, using any language you may know.

Show how to specify and execute a short program in the language from a command shell.

Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.

Aikido

<lang aikido> echo 'println ("Hello")' | aikido </lang>

ALGOL 68

Works with: ALGOL 68G version Any - tested with release mk15-0.8b.fc9.i386 - Interpret straight off
$ a68g -e 'print(("Hello",new line))'

Output:

Hello
Works with: ELLA ALGOL 68 version Any - tested with release 1.8.8d.fc9.i386 - translate to C and then compile and run

For an ELLA ALGOL 68 one-liner, merge these lines of shell code:

code='print(("Hello", new line))'
a=/tmp/algol$$ s=/usr/share/algol68toc;
echo -e "PROGRAM algol$$ CONTEXT VOID\nUSE standard\nBEGIN\n$code\nEND\nFINISH\n" > $a.a68 &&
a68toc -lib $s -dir $s -uname TMP -tmp $a.a68 && rm $a.a68 &&
gcc $s/Afirst.o $a.c  -l{a68s,a68,m,c} -o $a && rm $a.c &&
$a; rm $a

Output:

Hello

AutoHotkey

<lang autohotkey>RunWait, %comspec% /c systeminfo > tmp,,Hide FileRead, var, tmp FileDelete, tmp MsgBox,% var</lang>

AWK

Maybe the most common way one can use awk is from the command line for one-liners, feeding the interpreter with an input.

$ awk 'BEGIN { print "Hello"; }'

A more "complex" and "real" example:

$ awk '/IN/ { print $2, $4; }' <input.txt

Select field 2 and 4 of lines matching the regular expression /IN/ (i.e. where IN appears)

BASIC

The name of the BASIC executable will vary (common ones are basic, bas, and bwbasic), but in general, a short program can be piped to the interpreter like any other language: <lang shell>echo 'print "foo"'|basic</lang>

Note that under Windows (and presumably DOS) the two apostrophes (a.k.a. single quotes) should be omitted, since Windows doesn't remove them from the piped text (and the apostrophe is the comment character in many modern BASICs): <lang shell>echo print "foo"|basic</lang>

Also, some popular interpreters (including Michael Haardt's bas and Chipmunk Basic) will include an extra prompt before exiting unless you include exit or system (depending on the specific interpreter's syntax). This sample output shows both with and without system in bas:

erik@satan:~$ echo 'print "foo"'|bas
bas 2.2
Copyright 1999-2009 Michael Haardt.
This is free software with ABSOLUTELY NO WARRANTY.
> foo
> erik@satan:~$ echo 'print "foo":system'|bas
bas 2.2
Copyright 1999-2009 Michael Haardt.
This is free software with ABSOLUTELY NO WARRANTY.
> foo
erik@satan:~$

Note that this is rather specific to Unix-like systems; most DOS and Windows interpreters are generally unable to handle programs in this manner, unless they were ported from a *nix system in the first place.

ZX Spectrum Basic

On the ZX Spectrum, the ROM basic allows direct commands to be entered from the system prompt:

<lang zxbasic> PRINT "Hello World!" </lang>

C

Works with: gcc

The following code leaves the file a.out in the current directory (it does not delete it to avoid to call another shell/system dependent command/program). The current directory is not specified by ./ in every system...

$ echo 'main() {printf("Hello\n");}' | gcc -w -x c -; ./a.out

C#

Requires PowerShell 2:

> Add-Type -TypeDefinition "public class HelloWorld { public static void SayHi() { System.Console.WriteLine(""Hi!""); } }"
> [HelloWorld]::SayHi()
Hi!

Clojure

clj-env-dir comes with clojure-contrib.

<lang sh>$ clj-env-dir -e "(defn add2 [x] (inc (inc x))) (add2 40)"

  1. 'user/add2

42 </lang>

Common Lisp

Varies by implementation

Works with: SBCL

<lang sh>sbcl --noinform --eval '(progn (princ "Hello") (terpri) (quit))'</lang>

Works with: CLISP

<lang sh>clisp.exe -q -x "(progn (format t \"Hello from CLISP\") (quit))"</lang>

E

Some lines in this example are too long (more than 80 characters). Please fix the code if it's possible and remove this message.

<lang sh>rune --src.e 'println("Hello")'</lang>

The --src option ends with the the filename extension the provided type of program would have:

rune --src.e-awt 'def f := <swing:makeJFrame>("Hello"); f.show(); f.addWindowListener(def _{to windowClosing(_) {interp.continueAtTop()} match _{}}); interp.blockAtTop()'

Emacs Lisp

<lang sh>emacs -batch -eval '(princ "Hello World!\n")' </lang>

Or another example that does something useful: indent a C source file:

<lang sh>emacs -batch sample.c --eval '(indent-region (point-min) (point-max) nil)' -f save-buffer</lang>

Erlang

Erlang always starts other applications that can run in parallel in the background, and as such will not die by itself. To kill erl, we sequentially run the 'halt' function from the 'erlang' module (the -S is there to guarantee 'halt' will be evaluated after the io function).

$ erl -noshell -eval 'io:format("hello~n").' -s erlang halt
hello

F#

> echo printfn "Hello from F#" | fsi --quiet
Hello from F#

Factor

$ factor -run=none -e="USE: io \"hi\" print"

Forth

Works with: GNU Forth
$ gforth -e ".( Hello) cr bye"
Hello

Gema

$ gema -p '\B=Hello\n@end'
Hello

Groovy

Works with: UNIX Shell
$ groovysh -q "println 'Hello'"
Hello
C:\Users\user> groovysh -q "println 'Hello'"
Hello

Haskell

$ ghc -e 'putStrLn "Hello"'
Hello

J

$ jconsole -js "exit echo 'Hello'"
Hello

That said, note that J interpreters can themselves be thought of as command shells.

JavaScript

Works with: SpiderMonkey
$ js -e 'print("hello")'
hello

Lua

lua -e 'print "Hello World!"'

MATLAB

The command line in MATLAB acts just like the "main()" function in Java. It's a state machine. Variables declared in the scope of the command line persist in that scope until cleared from memory. So any thing you could do in a script, you can execute by directly input the desired commands into the command line. This first example declares and initializes an array named "a", which is stored in the scope of the MATLAB environment. Then the next command computes the mean of the elements in "a".

Example: <lang MATLAB>>> a = [1 2 3]; >> mean(a)

ans =

    2</lang> 

It is possible to declare a function in the command line thusly: <lang MATLAB>>> helloWorld = @()disp('Hello World'); >> helloWorld() Hello World</lang>


MUMPS

USER>WRITE !,"Hello nice people"

Hello, nice people
USER>DO HAPPY^ROSETTA(3)
 
The first 3 happy numbers are:
1
7
10

Objeck

Works with: UNIX Shell
./obc -run '"Hello"->PrintLine();' -dest hello.obe ; ./obr hello.obe

OCaml

$ ocaml <(echo 'print_endline "Hello"')
Hello

Oz

This is difficult to do in Oz because the compiler/interpreter always wants the source code in a file and does not read from stdin. We can do somethings like this on Unix-like systems:

echo >tmp.oz "{System.show hello}"; ozc -l System -e tmp.oz
hello

With -l System we make the System module available so that we can print something.

PARI/GP

<lang>system("ls")</lang>

Perl

$ perl -e 'print "Hello\n"'
Hello

Perl 6

Works with: Rakudo version #22 "Thousand Oaks"
$ perl6 -e 'say "Hello, world!"'
Hello, world!

PHP

assuming you have the PHP CLI (command-line interface) installed, not just the web server plugin

$ php -r 'echo "Hello\n";'
Hello

PicoLisp

<lang PicoLisp>$ picolisp -'prinl "Hello world!"' -bye Hello world!</lang>

Pike

<lang pike>$ pike -e 'write("Hello\n");' Hello</lang>

PowerShell

> powershell -Command "Write-Host 'Hello'"
Hello

PureBasic

Runs on Linux with(thanks to) bash. Path variables must be set as decribed in INSTALL.

$ echo 'messagerequester("Greetings","hello")' > "dib.pb" && ./pbcompiler dib.pb -e "dib" && ./dib

Python

$ python -c 'print "Hello"'
Hello

R

$ echo 'cat("Hello\n")' | R --slave
Hello

Alternatively, using the Rscript front-end,

$ Rscript -e 'cat("Hello\n")'
Hello

REBOL

rebview -vswq --do "print {Hello!} quit" 

Output:

Hello!

Retro

<lang Retro>echo '"hello\n" puts bye' | ./retro</lang>

REXX

<lang rexx> To execute a REXX program depends largely on the operating system.

Where REXX was originally developed (VM/CMS), there was native support for EXECs (which REXX is a type of), the REXX program had a filetype of 'EXEC' and all one needed to do to invoke it was to just enter its filename.

A REXX program may be named (say):

             SOMESUCH  EXEC      A1

SOMESUCH is the filename EXEC is the filetype (the file extension) A1 is the filemode (A would be like a harddrive letter)


To execute it, enter: </lang> <lang rexx> [VM/CMS] SOMESUCH ...optionalParameters... ──or── [VM/CMS] EXEC SOMESUCH ...optionalParameters... </lang> <lang rexx> In MVS/TSO, 'SOMESUCH' would be placed in an appropiate PDS (partitioned dataset) library, and the following command could be issued: </lang> <lang rexx> [MVS/TSO] SOMESUCH </lang> <lang rexx> In CMS (VM), TSO (MVS), and OS/2 (among others in the IBM family), the REXX interpretor is built in the operating system.

In DOS (under Windows or not), most REXX interpretors assume a REXX program has a particular file extension (or one of serveral extensions, 'REX', 'REXX', 'CMD' being the most common), and to invoke a REXX interpretor to execute (interpret) a REXX program, the name of the REXX interpreter is issued followed by the REXX program name (and followed by any optional parameters).

Alternatively, in the Windows/NT family of operating systems (which includes 2000, XP, Vista, 7, and up), a program can be associated with a file's extension, so when the following is issued </lang> <lang rexx> [Windows DOS] SOMESUCH </lang> <lang rexx> Windows (or DOS) would look in the usual places (usually starting in the current directory (CD), and including, but not limited to the PATH, it would find

            SOMESUCH.REX      (for instance),

and noted that files with such file extension should be executed with the program (say):

      REXX.EXE       ───or───
      REGINA.EXE     ───or───
      R4.EXE         (just to name a few examples, but only one could be used),

which itself, could be in the PATH or be specified as a specific file such as

         C:\LANGUAGES\REXX\REXX.EXE         ─── (just an example).

</lang>

Ruby

$ ruby -e 'puts "Hello"'
Hello

Scala

C:\>scala -e "println(\"Hello\")"
Hello

The escaping of quotes is required by Windows. On Unix, one could just use single quotes around the code. In either case, any required libraries should have their JAR files pointed at by the environment variable CLASSPATH.

Slate

<lang slate>./slate --eval "[inform: 'hello'] ensure: [exit: 0].".</lang>

SNOBOL4

Portable version <lang snobol>echo 'a output = "Hello, World!";end' | snobol4 -b</lang>

Bash version <lang snobol>snobol4 -b <<<'a output = "Hello, World!";end'</lang>


Tcl

This is an area where Tcl is lacking, though when shell one-liners are required a construct like this is typically used:

$ echo 'puts Hello' | tclsh
Hello

(This apparent weakness is purposeful; it leaves a larger fraction of the space of possible arguments open to use by the script being executed.)

UNIX Shell

Works with: Bash
$ bash -c ls 
$ bash -c "echo hello" 

Ursala

The command to execute the Ursala compiler is fun. An expression supplied as a parameter to the --main option is compiled and evaluated. If the expression evaluates to a list of character strings, it can be displayed on standard output with --show. If it's some other type, it can be formatted for display by --cast <type expression>,

$ fun --main=-[hello]- --show
hello
$ fun --main="power/2 32" --cast %n
4294967296
$ fun --m="..mp2str mpfr..pi 120" --c %s
'3.1415926535897932384626433832795028847E+00'