Shell one-liner: Difference between revisions
m →{{header|REXX}}: removed STYLE from the PRE html tag. |
|||
Line 479: | Line 479: | ||
echo do j=10 by 20 for 4;say right('hello',j);end | regina</lang> |
echo do j=10 by 20 for 4;say right('hello',j);end | regina</lang> |
||
'''output''' when using the (above) from the command line: |
'''output''' when using the (above) from the command line: |
||
<pre> |
|||
<pre style="overflow:scroll"> |
|||
hello |
hello |
||
hello |
hello |
Revision as of 00:34, 10 November 2014
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
You are encouraged to solve this task according to the task description, using any language you may know.
Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length.
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.
ACL2
<lang bash>$ acl2 <<< '(cw "Hello.")'</lang>
Ada
under a unixoid shell (bash, sh, ...)
<lang bash>echo 'with Ada.text_IO; use Ada.text_IO; procedure X is begin Put("Hello!"); end X;' > x.adb; gnatmake x; ./x; rm x.adb x.ali x.o x</lang>
Note that this mercilessly overwrites and later deletes any files x.adb, x.ali, x,o and x in the current directory.
Aikido
<lang aikido>echo 'println ("Hello")' | aikido</lang>
Aime
<lang sh>$ src/aime -c 'o_text("Hello, World!\n");'</lang>
ALGOL 68
<lang bash>$ a68g -e 'print(("Hello",new line))'</lang> Output:
Hello
For an ELLA ALGOL 68 one-liner, merge these lines of shell code: <lang bash>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</lang> Output:
Hello
AWK
Maybe the most common way one can use awk is from the command line for one-liners, feeding the interpreter with an input. <lang bash>$ awk 'BEGIN { print "Hello"; }'</lang>
A more "complex" and "real" example: <lang bash>$ awk '/IN/ { print $2, $4; }' <input.txt</lang>
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 bash>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 dos>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>
Bracmat
This example uses the predefined function tay
to make a taylor expansion of e^x
.
DOS: <lang bracmat>bracmat "put$tay$(e^x,x,20)&"</lang> Linux: <lang bracmat>bracmat 'put$tay$(e^x,x,10)&'</lang> Output:
1 + x + 1/2*x^2 + 1/6*x^3 + 1/24*x^4 + 1/120*x^5 + 1/720*x^6 + 1/5040*x^7 + 1/40320*x^8 + 1/362880*x^9 + 1/3628800*x^10 + 1/39916800*x^11 + 1/479001600*x^12 + 1/6227020800*x^13 + 1/87178291200*x^14 + 1/1307674368000*x^15 + 1/20922789888000*x^16 + 1/355687428096000*x^17 + 1/6402373705728000*x^18 + 1/121645100408832000*x^19 + 1/2432902008176640000*x^20
Burlesque
<lang> Burlesque.exe --no-stdin "5 5 .+" </lang>
Using the official interpreter.
C
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... <lang bash>$ echo 'main() {printf("Hello\n");}' | gcc -w -x c -; ./a.out</lang>
C#
Note: whilst small, this is more than one line.
Requires PowerShell 2: <lang powershell>> Add-Type -TypeDefinition "public class HelloWorld { public static void SayHi() { System.Console.WriteLine(""Hi!""); } }" > [HelloWorld]::SayHi() Hi!</lang>
Clojure
Note: whilst small, this is more than one line.
clj-env-dir comes with clojure-contrib.
<lang bash>$ clj-env-dir -e "(defn add2 [x] (inc (inc x))) (add2 40)"
- 'user/add2
42</lang>
CMake
This only works with Unix systems that have the device node /dev/stdin
.
<lang bash>echo 'message(STATUS "Goodbye, World!")' | cmake -P /dev/stdin</lang>
Common Lisp
Varies by implementation
<lang bash>sbcl --noinform --eval '(progn (princ "Hello") (terpri) (quit))'</lang>
<lang bash>clisp.exe -q -x "(progn (format t \"Hello from CLISP\") (quit))"</lang>
D
requires rdmd <lang d>rdmd --eval="writeln(q{Hello World!})"</lang>
Hello World!
Dc
<lang bash>dc -e '22 7/p'</lang>
E
<lang bash>rune --src.e 'println("Hello")'</lang>
The --src
option ends with the the filename extension the provided type of program would have:
<lang>rune --src.e-awt 'def f := <swing:makeJFrame>("Hello"); f.show(); f.addWindowListener(def _{to windowClosing(_) {interp.continueAtTop()} match _{}}); interp.blockAtTop()'</lang>
Emacs Lisp
<lang bash>emacs -batch -eval '(princ "Hello World!\n")' </lang> Or another example that does something useful: indent a C source file: <lang bash>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). <lang bash>$ erl -noshell -eval 'io:format("hello~n").' -s erlang halt hello</lang>
F#
<lang cmd>> echo printfn "Hello from F#" | fsi --quiet Hello from F#</lang>
Factor
<lang bash>$ factor -run=none -e="USE: io \"hi\" print"</lang>
Forth
<lang bash>$ gforth -e ".( Hello) cr bye" Hello</lang>
Fortran
This example, stolen from the c example is subject to the same caveats. While contrived, FORTRAN as a one liner can easily handle some unique tasks. Let's plot a Bessel function: <lang bash> $ gawk 'BEGIN{print"write(6,\"(2(g12.3,x))\")(i/10.0,besj1(i/10.0), i=0,1000)\nend";exit(0)}'|gfortran -ffree-form -x f95 - | gnuplot -p -e 'plot "<./a.out" t "Bessel function of 1st kind" w l' </lang> Sorry, I don't know how to upload my jpeg file for the Image tag. Let's use the dumb display instead.
0.6 +*------------+-------------+------------+-------------+------------++ +** + + Bessel function of 1st kind ****** + 0.5 +** ++ |** | 0.4 +** ++ * * | 0.3 *+* * ++ * * ** * | 0.2 *+* *** ** ** ++ 0.1 *+* * * ** ** *** ** ** * ** * ++ * ** * * *** ** * * *** ** *** ** ** *** ** ** *** ** ** | 0 *+ * * * * * * * * * * * *** * * * * *** * * *** *** * * *** ***+ | * * * * *** * * * * *** * * * * *** *** * * **** *** *** *** *| -0.1 ++ * * * * ** *** *** ** ** *** ** ** ** ** ** ** ** ** | *** *** ** ** ** ** * * | -0.2 ++ ** ** ** ++ | ** * | -0.3 ++ ** ++ + ** + + + + + -0.4 ++------------+-------------+------------+-------------+------------++ 0 20 40 60 80 100
Gema
<lang bash>$ gema -p '\B=Hello\n@end' Hello</lang>
Go
Go is first of all a compiled language and currently comes with no support for running as a script language. The compiler and linker can of course be run from a command line shell, as in, <lang bash>echo 'package main;func main(){println("hllowrld")}'>8.go;8g 8.go;8l 8.8;8.out</lang> This will overwrite existing files in the current directory 8.go, 8.8, and 8.out, assuming of course, that the the current directory is even writable, and will leave these files behind after executing.
Running Go as a script language is a popular request however, and one of the better solutions currently is gorun. Gorun has solutions for the temporary file problem, writing to best-guess temporary directories by default and having an option to specify the location when this is needed or desired. Gorun still expects to read the source code from a file however, so you are on your own to deal with this before passing the file to gorun. Example, <lang bash>echo 'package main;func main(){println("hllowrld")}'>/tmp/8.go;gorun /tmp/8.go</lang> Output from either example:
hllowrld
Groovy
<lang bash>$ groovysh -q "println 'Hello'" Hello</lang>
<lang cmd>C:\Users\user> groovysh -q "println 'Hello'" Hello</lang>
Haskell
<lang bash>$ ghc -e 'putStrLn "Hello"' Hello</lang>
Icon and Unicon
These examples work with posix shells.
<lang icon>echo "procedure main();write(\"hello\");end" | icont - -x</lang>
<lang unicon>echo "procedure main();write(\"hello world\");end" >hello.icn; unicon hello.icn -x</lang>
J
<lang bash>$ jconsole -js "exit echo 'Hello'" Hello</lang>
That said, note that J interpreters can themselves be thought of as command shells.
Java
These three lines work with Bourne Shell (or compatible) or C Shell (or compatible), or bash on Unix/Linux/MacOSX/Windows+cygwin
<lang bash>$ echo 'public class X{public static void main(String[]args){' \ > 'System.out.println("Hello Java!");}}' >X.java $ javac X.java && java X</lang>
A user can also enter this as one (very long) line:
<lang bash>$ echo 'public class X{public static void main(String[]args){System.out.println("Hello Java!");}}'>X.java;javac X.java&&java X</lang>
Compatible Environments (such as cmd.exe)
Works with cmd.exe on Windows (tested on Microsoft Windows XP [Version 5.1.2600]) <lang cmd>C:\>echo public class X{public static void main(String[] args){System.out.println("Hello Java!");}}>X.java&&javac X.java&&java X Hello Java!</lang>
JavaScript
<lang bash>$ js -e 'print("hello")' hello</lang>
Julia
<lang julia>$ julia -e 'for x in ARGS; println(x); end' foo bar foo bar</lang>
K
<lang bash>$ k -e "\`0: \"hello\\n\""</lang>
Lasso
From stdin:
<lang Lasso>echo " 'The date and time is: ' + date " | lasso9 --</lang>
Or alternatively:
<lang Lasso>$ lasso9 -s " 'The date and time is: ' + date "</lang>
Liberty BASIC
<lang lb> echo print "hello">oneLiner.bas & liberty -r oneLiner.bas echo print "hello">oneLiner.bas & liberty -r oneLiner.bas </lang>
Lua
<lang bash>lua -e 'print "Hello World!"'</lang>
Maple
<lang bash>maple -c'print(HELLO);' -cquit</lang>
Mathematica
<lang Mathematica>echo Print[2+2] > file & math.exe -script file</lang>
NetRexx
Create a temporary file, execute the file via the NetRexx interpreter then delete the temporary file and any files generated via the translation. (i.e. Java class files etc.) <lang bash> $ TNRX=`mktemp T_XXXXXXXXXXXX` && test ! -e $TNRX.* && (echo 'say "Goodbye, World!"' >$TNRX; nrc -exec $TNRX; rm $TNRX $TNRX.*; unset TNRX) </lang>
Output:
NetRexx portable processor, version NetRexx 3.01, build 40-20120823-0156 Copyright (c) RexxLA, 2011,2012. All rights reserved. Parts Copyright (c) IBM Corporation, 1995,2008. Program T_dO7RQs5HPElq ===== Exec: T_dO7RQs5HPElq ===== Goodbye, World! Processing of 'T_dO7RQs5HPElq' complete
NewLISP
<lang NewLISP>newlisp -e "\"Hello\" ->"Hello"</lang>
Nimrod
echo 'for i in 0..10: echo "Hello World"[0..i]' | nimrod i >>> H He Hel Hell Hello Hello Hello W Hello Wo Hello Wor Hello Worl Hello World >>>
Objeck
<lang bash>./obc -run '"Hello"->PrintLine();' -dest hello.obe ; ./obr hello.obe</lang>
OCaml
<lang bash>$ ocaml <(echo 'print_endline "Hello"') Hello</lang>
Octave
<lang matlab>$ octave --eval 'printf("Hello World, it is %s!\n",datestr(now));' Hello World, it is 28-Aug-2013 17:53:47!</lang>
ooRexx
<lang bash> rexx -e "say 'Goodbye, world.'" </lang>
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: <lang bash>echo >tmp.oz "{System.show hello}"; ozc -l System -e tmp.oz hello</lang>
With -l System
we make the System module available so that we can print something.
PARI/GP
<lang bash>echo "print(Pi)" | gp -q</lang>
Pascal
<lang bash>$ echo "begin writeln('Hello World') end." >OneLiner.pas; fpc -Fe/dev/null OneLiner.pas; ./OneLiner Hello World</lang>
Perl
<lang bash>$ perl -e 'print "Hello\n"' Hello</lang>
More information about the many ways of invoking perl can be found in perlrun.
Perl 6
<lang bash>$ perl6 -e 'say "Hello, world!"' Hello, world!</lang>
PHP
assuming you have the PHP CLI (command-line interface) installed, not just the web server plugin <lang bash>$ php -r 'echo "Hello\n";' Hello</lang>
PicoLisp
<lang PicoLisp>$ picolisp -'prinl "Hello world!"' -bye Hello world!</lang>
Pike
<lang bash>$ pike -e 'write("Hello\n");' Hello</lang>
PowerShell
<lang cmd>> powershell -Command "Write-Host 'Hello'" Hello</lang>
Prolog
Command-Line Options
<lang prolog>$ swipl -g "writeln('hello world')." -t 'halt.' hello world $</lang> <lang prolog>$ gprolog --init-goal "write('goodbye'),nl,halt" goodbye $</lang> <lang prolog>$ yap -q -g "current_prolog_flag(dialect, D), writeln(D), halt" yap</lang>
<<<
<lang prolog>$ swipl -q <<< "current_prolog_flag(dialect,D), writeln(D), halt." swi
$ yap -q <<< "current_prolog_flag(dialect,D), writeln(D), halt." yap</lang>
Pipe
<lang prolog>$ echo "current_prolog_flag(dialect,D), writeln(D), halt." | swipl -q swi
$ echo "current_prolog_flag(dialect,D), writeln(D), halt." | yap -q yap</lang>
PureBasic
Runs on Linux with(thanks to) bash. Path variables must be set as decribed in INSTALL. <lang bash>$ echo 'messagerequester("Greetings","hello")' > "dib.pb" && ./pbcompiler dib.pb -e "dib" && ./dib</lang>
Python
Prints "Hello"
<lang bash>$ python -c 'print "Hello"' Hello</lang>
Web server with CGI
The python CGIHTTPServer module is also an executable library that performs as a web server with CGI. to start enter: <lang bash>python -m CGIHTTPServer</lang> It returns with:
Serving HTTP on 0.0.0.0 port 8000 ...
R
<lang bash>$ echo 'cat("Hello\n")' | R --slave Hello</lang>
Alternatively, using the Rscript front-end, <lang bash>$ Rscript -e 'cat("Hello\n")' Hello</lang>
Racket
<lang bash>$ racket -e "(displayln \"Hello World\")" Hello World</lang>
REBOL
<lang bash>rebview -vswq --do "print {Hello!} quit" </lang>
Output:
Hello!
Retro
<lang Retro>echo '"hello\n" puts bye' | ./retro</lang>
REXX
Note: "Regina" is the only version of REXX that supports this type of behavior (taking it's input from a console stream). <lang rexx> ┌────────────────────────────────────────────────┐
│ from the MS Windows® command line (cmd.exe) │ └────────────────────────────────────────────────┘
echo do j=10 by 20 for 4;say right('hello',j);end | regina</lang> output when using the (above) from the command line:
hello hello hello hello
Ruby
From Unix: <lang bash>$ ruby -e 'puts "Hello"' Hello</lang>
<lang bash>$ jruby -e 'puts "Hello from JRuby"' Hello from JRuby</lang>
<lang bash>$ rbx -e 'puts "Hello from Rubinius"' Hello from Rubinius</lang>
Run BASIC
<lang bash>print shell$("echo hello world")</lang>
Scala
<lang cmd>C:\>scala -e "println(\"Hello\")" Hello</lang> <lang cmd> PS C:\> scala -e 'println(\"Hello\")' Hello</lang>
The escaping of quotes is required by Windows. On Unix and shown in the example on Windows PowerShell, one could just use single quotes around the code.
Scheme
<lang scheme>guile -c '(display "Hello, world!\n")'</lang>
Shiny
<lang shiny>shiny -e "say 'hi'" </lang>
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: <lang bash>$ echo 'puts Hello' | tclsh Hello</lang>
TXR
<lang bash>$ echo 123-456-7890 | txr -c '@a-@b-@c' - a="123" b="456" c="7890" </lang>
Most useful txr queries consist of multiple lines, and the line structure is important. Multi-liners can be passed via -c
easily, but there is no provision in the syntax that would allow multi-liners to be actually written as one physical line. There are opposite provisions for splitting long logical lines into multiple physical lines.
The -e
(evaluate) and -p
(evaluate and print) options provide shell one-liner access to
TXR Lisp:
<lang bash>$ txr -p '(+ 2 2)' 4</lang>
<lang bash>$ txr -e '(mkdir "foo" #o777)' $ ls -ld foo drwxrwxr-x 2 kaz kaz 4096 Mar 4 23:36 foo</lang>
UNIX Shell
Explicit call of the shell, passing the shell command via the -c
option:
<lang bash>$ sh -c ls</lang>
<lang bash>$ sh -c "echo hello"</lang>
To invoke a specific shell like Bash, Korn Shell or Z Shell:
<lang bash>$ bash -c 'paste <(echo 1) <(echo 2)' $ ksh -c 'let i=3+4; print $i' $ zsh -c 'if 5 -lt 6 { echo ok };'</lang>
Shell scripts almost never use sh -c
, because there are various implicit ways whereby the shell command language evaluates a command in a subshell:
<lang bash>$ VAR=`echo hello` # obsolescent backtick notation $ VAR=$(echo hello) # modern POSIX notation $ (echo hello) # execute in another shell process, not in this one</lang>
There are more details about `echo hello`
and $(echo hello)
at Execute a system command#UNIX Shell.
C Shell
Run a C shell command from any shell:
<lang bash>$ csh -fc 'if (5 < 6) echo ok'</lang>
es
Run a command, in extensible shell, from any shell:
<lang bash>$ es -c 'if {test 5 -lt 6} {echo ok}'</lang>
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>,
<lang bash>$ fun --main=-[hello]- --show hello $ fun --main="power/2 32" --cast %n 4294967296 $ fun --m="..mp2str mpfr..pi 120" --c %s '3.1415926535897932384626433832795028847E+00'</lang>
Vedit macro language
The following DOS command starts Vedit and displays a message. When the user presses any key, Vedit exits. <lang cmd>vpw -c'Get_Key("Hello!") exit'</lang>
Wart
<lang bash>echo "prn 34" |wart</lang>
zkl
With a unix like shell, just pipe the program into the REPL. Kinda greasy and noisy. To shut it up, send stdout to /dev/null <lang bash>echo 'println("Hello World ",5+6)' | zkl</lang>
- Output:
zkl 1.12.9, released 2014-05-01 Hello World 11 Hello World 11
- Programming Tasks
- Programming environment operations
- ACL2
- Ada
- Aikido
- Aime
- ALGOL 68
- AWK
- BASIC
- ZX Spectrum Basic
- Bracmat
- Burlesque
- C
- C sharp
- Clojure
- CMake
- Common Lisp
- D
- Dc
- E
- Emacs Lisp
- Erlang
- F Sharp
- Factor
- Forth
- Fortran
- Gema
- Go
- Groovy
- Haskell
- Icon
- Unicon
- J
- Java
- JavaScript
- Julia
- K
- Lasso
- Liberty BASIC
- Lua
- Maple
- Mathematica
- NetRexx
- NewLISP
- Nimrod
- Objeck
- OCaml
- Octave
- OoRexx
- Oz
- PARI/GP
- Pascal
- Perl
- Perl 6
- PHP
- PicoLisp
- Pike
- PowerShell
- Prolog
- PureBasic
- Python
- R
- Racket
- REBOL
- Retro
- REXX
- Ruby
- Run BASIC
- Scala
- Scheme
- Shiny
- Slate
- SNOBOL4
- Tcl
- TXR
- UNIX Shell
- C Shell
- Es
- Ursala
- Vedit macro language
- Wart
- Zkl
- AutoHotkey/Omit
- Java/Omit
- Maxima/Omit
- Modula-3/Omit
- TI-83 BASIC/Omit
- TI-89 BASIC/Omit