87
\$\begingroup\$

One of the most common standard tasks (especially when showcasing esoteric programming languages) is to implement a "cat program": read all of STDIN and print it to STDOUT. While this is named after the Unix shell utility cat it is of course much less powerful than the real thing, which is normally used to print (and concatenate) several files read from disc.

Task

You should write a full program which reads the contents of the standard input stream and writes them verbatim to the standard output stream. If and only if your language does not support standard input and/or output streams (as understood in most languages), you may instead take these terms to mean their closest equivalent in your language (e.g. JavaScript's prompt and alert). These are the only admissible forms of I/O, as any other interface would largely change the nature of the task and make answers much less comparable.

The output should contain exactly the input and nothing else. The only exception to this rule is constant output of your language's interpreter that cannot be suppressed, such as a greeting, ANSI color codes or indentation. This also applies to trailing newlines. If the input does not contain a trailing newline, the output shouldn't include one either! (The only exception being if your language absolutely always prints a trailing newline after execution.)

Output to the standard error stream is ignored, so long as the standard output stream contains the expected output. In particular, this means your program can terminate with an error upon hitting the end of the stream (EOF), provided that doesn't pollute the standard output stream. If you do this, I encourage you to add an error-free version to your answer as well (for reference).

As this is intended as a challenge within each language and not between languages, there are a few language specific rules:

  • If it is at all possible in your language to distinguish null bytes in the standard input stream from the EOF, your program must support null bytes like any other bytes (that is, they have to be written to the standard output stream as well).
  • If it is at all possible in your language to support an arbitrary infinite input stream (i.e. if you can start printing bytes to the output before you hit EOF in the input), your program has to work correctly in this case. As an example yes | tr -d \\n | ./my_cat should print an infinite stream of ys. It is up to you how often you print and flush the standard output stream, but it must be guaranteed to happen after a finite amount of time, regardless of the stream (this means, in particular, that you cannot wait for a specific character like a linefeed before printing).

Please add a note to your answer about the exact behaviour regarding null-bytes, infinite streams, and extraneous output.

Additional rules

  • This is not about finding the language with the shortest solution for this (there are some where the empty program does the trick) - this is about finding the shortest solution in every language. Therefore, no answer will be marked as accepted.

  • Submissions in most languages will be scored in bytes in an appropriate preexisting encoding, usually (but not necessarily) UTF-8.

    Some languages, like Folders, are a bit tricky to score. If in doubt, please ask on Meta.

  • Feel free to use a language (or language version) even if it's newer than this challenge. Languages specifically written to submit a 0-byte answer to this challenge are fair game but not particularly interesting.

    Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language.

    Also note that languages do have to fulfil our usual criteria for programming languages.

  • If your language of choice is a trivial variant of another (potentially more popular) language which already has an answer (think BASIC or SQL dialects, Unix shells or trivial Brainfuck derivatives like Headsecks or Unary), consider adding a note to the existing answer that the same or a very similar solution is also the shortest in the other language.

  • Unless they have been overruled earlier, all standard rules apply, including the http://meta.codegolf.stackexchange.com/q/1061.

As a side note, please don't downvote boring (but valid) answers in languages where there is not much to golf; these are still useful to this question as it tries to compile a catalogue as complete as possible. However, do primarily upvote answers in languages where the author actually had to put effort into golfing the code.

Catalogue

The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

## Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

## Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

## Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the snippet:

## [><>](http://esolangs.org/wiki/Fish), 121 bytes

<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 62230; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 8478; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "//api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "//api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(42), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>

\$\endgroup\$
  • 55
    \$\begingroup\$ Bash, 3 bytes: cat \$\endgroup\$ – TheDoctor Oct 31 '15 at 19:02
  • 3
    \$\begingroup\$ @TheDoctor I guess this would fall into the "don't use a builtin which does exactly what is needed" rule. \$\endgroup\$ – Paŭlo Ebermann Oct 31 '15 at 19:46
  • 5
    \$\begingroup\$ @PaŭloEbermann There is no such rule, and the corresponding standard loophole is no longer accepted. (In fact, there is already a sh answer using cat which also contains a shorter solution using dd.) \$\endgroup\$ – Martin Ender Oct 31 '15 at 20:25
  • 1
    \$\begingroup\$ If only it used standard methods of input and output: ///, 0 bytes. \$\endgroup\$ – Comrade SparklePony Mar 31 '17 at 19:33
  • 1
    \$\begingroup\$ @SparklePony Except, you'd have to escape slashes and backslashes. \$\endgroup\$ – Martin Ender Mar 31 '17 at 20:35

273 Answers 273

1
4 5
6
7 8
10
1
\$\begingroup\$

Reng v.1.2, 4 bytes

is~o

This takes input, skips if not a negative one (i.e. no input found). When s find a regular character, it skips over the ~ and outputs the input with o. Otherwise, it meets the ~ and ends execution. Input is like "string1" "string2" ... "stringN". Try it here!

The following 13-byte program allows you to feed input more than once, but only yields correct output provided you feed it in at the right time.

>isvo
/$$>is!

Input "Meow":

meoowww

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Jelly, 1 byte

¹

Simply the identity function.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Lua, 30 Bytes

Heavily base upon Lynn's answer, but as it is not updated anymore, I'll feel free ot post this 30 bytes answer.

::a::io.write(io.read())goto a
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Fuzzy Octo Guacamole, 3 bytes

(non-competing, FOG is newer than the challenge)

(^)

Looks emotish (that's totally a word).

The ^ gets input, the X pops it and prints it.

The ( and ) denote the start and end of an infinite loop.

4 byte solution with a for loop:

?[?^]

The [ and ] denote a for loop, and the ? increments the counter, so it never runs out.

Weird implicit outputs means it prints the outputs automatically.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Cool!!!!!!!!!!! \$\endgroup\$ – Conor O'Brien Mar 18 '16 at 22:28
  • \$\begingroup\$ This is the infinite cat challenge. If it is at all possible in your language to support an arbitrary infinite input stream (i.e. if you can start printing bytes to the output before you hit EOF in the input), your program has to work correctly in this case. \$\endgroup\$ – Dennis Mar 19 '16 at 4:57
1
\$\begingroup\$

Javascript (browser), 16 15 bytes

alert(prompt())
| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ I like the rules abuse here... :-) By the way, you can save a byte by dropping the semicolon - JavaScript has automatic semicolon insertion, with only a few exceptions. Also, you probably should specify state this is for browsers only, since Node.js doesn't have either of these, but it does support console IO. \$\endgroup\$ – Isiah Meadows May 20 '16 at 1:50
  • \$\begingroup\$ Done! Thanks for the edit btw \$\endgroup\$ – OldBunny2800 May 20 '16 at 1:52
  • 1
    \$\begingroup\$ Welcome! <filler to make SE happy> \$\endgroup\$ – Isiah Meadows May 20 '16 at 1:53
1
\$\begingroup\$

Archway, 7 bytes

/.\
\,/

According to Esolangs, this is the only useful program that can be written in the original Archway language.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Archway 2, 19 bytes

   \
// .
  , /
+/\
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

APL, 6 bytes

⎕←⍞
→1

This has worked in all APLs since the beginning of time.

wait for input
⎕← Output that
→1 go to line 1

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Wat, 6 + 1 = 7 bytes

åó#ÐÑÅ

(This code don't have any rapport with DNA)

Explanation:

åó#ÐÑÅ

å      Read a character
 ó     Duplicate the top of the stack
  #    Skip the next character
   Ð   End the program
    Ñ  If the top of the stack is 0, go backward (execute Ð and end the program), otherwise go forward
     Å Print the character on the top of the stack
       After, the IP wrap and the line is reexecuted
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Omam, 137 bytes

the screams all sound the same
though the truth may vary
don't listen to a word i say
the screams all sound the same
this ship will carry

Note that I haven't copied it. In fact, I added this code there today.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Well, this is a beautiful language. \$\endgroup\$ – user8397947 Jun 29 '16 at 1:06
  • \$\begingroup\$ @dorukayhan It's in fact BF, but with different commands. Note that this, technically, is 5 lines, i.e. 5 commands. BF golfing tips apply. \$\endgroup\$ – Erik the Outgolfer Jun 29 '16 at 7:45
1
\$\begingroup\$

Tellurium, 2 bytes

i^

Pretty simple, eh?

What it does is get input from the user using the i command, and stores it in the tape in the currently selected item (in the code above, it's 0, the default).

After that, it prints the currently selected item's value using the ^ command. (whatever the user input).

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Apps Script + Google Sheets, 29 bytes

Script

function Q(s){return s}

Sheet

=q(B1)

Cell B1 is the input.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ By convention A1 is the input cell for cell-based languages, and you should be able to reduce =q(b1) to =q(A1 where Google Sheets will autoformat in the terminating ) \$\endgroup\$ – Taylor Scott Sep 5 '17 at 16:09
1
\$\begingroup\$

J, 14 bytes

stdout]stdin''

Reads the entire input from stdin until EOF is reached and store it as an array of characters. Then output all of it to stdout. This will work when saved as a script to be run using jconsole, where scripts are programs for interpreted languages.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Fith, 7 bytes

read \.

read gets input from STDIN. The language cannot handle infinite streams. \. prints the string on top of the stack without a trailing newline.

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ Can't do read\.? \$\endgroup\$ – Erik the Outgolfer Jun 29 '16 at 13:28
  • \$\begingroup\$ @EʀɪᴋᴛʜᴇGᴏʟғᴇʀ No. Fith's identifier rules are very lax, so read\. would be counted as a single token. \$\endgroup\$ – jqblz Jun 29 '16 at 16:18
  • 1
    \$\begingroup\$ And why can't you do read . then? \$\endgroup\$ – Erik the Outgolfer Jun 29 '16 at 16:24
  • \$\begingroup\$ @EʀɪᴋᴛʜᴇGᴏʟғᴇʀ That adds a newline at the end of the string. My understanding was that that shouldn't happen. \$\endgroup\$ – jqblz Jun 29 '16 at 16:27
  • \$\begingroup\$ Oh, okay then.. \$\endgroup\$ – Erik the Outgolfer Jun 29 '16 at 16:28
1
\$\begingroup\$

BruhScript, 22 bytes

Source:

↺₀1Λ₀⍈+⍰'
∇

Encoded version hexdump:

0000000: 0099 009a 003a 0087 009a 008f 0051 008e  .....:.......Q..
0000010: 0061 0000 0069                           .a...i

Explanation:

↺                While loop. Take two niladic functions as arguments.
 ₀1Λ             A function that always return 1
    ₀⍈+⍰'<LF>∇   `'<c>` is a shorthand for «<c>», so this code print (⍈) the input (⍰) + a newline ('<LF>), and return None (∇)
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Clojure, 18 bytes

(print(read-line))

This 30-bytes program runs forever:

(while true(print(read-line)))
| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ Wouldn't this only read and print a single line? I'm pretty sure Clojure would be able to deal with arbitrary finite and even infinite streams instead. \$\endgroup\$ – Martin Ender Jun 4 '16 at 20:52
  • \$\begingroup\$ Wouldn't this only read and print a single line? 24 days later, I worked around it. \$\endgroup\$ – user8397947 Jun 29 '16 at 1:11
  • \$\begingroup\$ @dorukayhan It ((while true) still (prints a (read-line)))! You need to support infinite input without newlines if you can. \$\endgroup\$ – Erik the Outgolfer Jun 29 '16 at 16:26
  • \$\begingroup\$ @EʀɪᴋᴛʜᴇGᴏʟғᴇʀ Well, considering Clojure is Java in disguise, (read-line) uses System.in, which can theoretically take infinitely many bytes. \$\endgroup\$ – user8397947 Jun 29 '16 at 16:30
  • 1
    \$\begingroup\$ Badly overdue disclaimer: This might be the first Clojure program I wrote \$\endgroup\$ – user8397947 Jun 29 '16 at 16:59
1
\$\begingroup\$

C++ (109 Bytes)

Thanks to Eʀɪᴋ ᴛʜᴇ Gᴏʟғᴇʀ for reducing 4 bytes.

#include <iostream>
#include <string>
using namespace std;main(){string A,W;while(cin>>A)W+=A;cout<<W<<endl;}
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Can't you remove it though? Also, if I'm correct, char*A is -2 string A. That way then, I think, you can remove #include <string>\n for -18, and use #include<iostream> for -1. Also, since you will use std:: 2-3 times, you can remove using namespace std;, and replace cin, cout (and possibly endl?) with std::cin, std::cout and possible std::endl. \$\endgroup\$ – Erik the Outgolfer Jun 29 '16 at 13:26
1
\$\begingroup\$

Racket, 52 bytes

A classical approach.

(copy-port(current-input-port)(current-output-port))

In Racket, default settings are stored in parameters which are invoked to obtain their value (or invoked with an argument to set them). This mechanism is also used to access/set the default input and output ports.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Python 3, 21 bytes

print(input(),end='')
| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ This doesn't support multiple lines nor an infinite stream \$\endgroup\$ – Blue Sep 27 '16 at 18:17
  • 1
    \$\begingroup\$ Also, why not use print(end=input())? :P \$\endgroup\$ – FlipTack Dec 30 '16 at 10:57
1
\$\begingroup\$

Pyke, 2 bytes

zr

Try it here!

z  - read_line()
 r - if no error: goto_start()
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Jelly, 5 bytes

ƈȮøL¿

Try it online!

This one is valid, unlike the other 1-byte one, which is 100% invalid:

¹

(command-line arg, not STDIN)

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Thanks to Dennis for implementing EOF detection for that. \$\endgroup\$ – Erik the Outgolfer Sep 28 '16 at 15:35
1
\$\begingroup\$

reticular, 2 bytes

ip

This exits with an error, but works fine. Try it online!

ip
i   take a line of input (no newline)
 p  print it with a newline after
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

ABCR, 4 bytes

5cQx

Explanation:

5      while(peek(B)){  //Queue B peeks default to 1, so this infinite-loops
 c        dequeue(c)  // Queue C dequeues default to an input character if C is empty
  Q       print(c)   /* Prints peek at the queue, and peeks on an empty queue C
                        default to the register value, which was set by `c` */
   x    }
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

QBIC, 4 bytes

_??A

Unfortunately, QBasic (and by extension QBIC) doesn't handle input very well. Comma's are only allowed if quotes are used (which then get stripped from the output). Newlines are another no-go.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Emotinomicon, 16 bytes

⏫😎⏪⏬⏩

Explanation:

⏫😎⏪⏬⏩
⏫             Get input
  😎           Reverse Stack
    ⏪  ⏩     Loop
      ⏬       Output one char
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ There is alerady a shorter answer. \$\endgroup\$ – Erik the Outgolfer Oct 9 '16 at 11:12
  • \$\begingroup\$ Yes but if input multiple chars in the input popup the output is reversed \$\endgroup\$ – Roman Gräf Oct 19 '16 at 8:57
1
\$\begingroup\$

C#, 79 bytes

using x=System.Console;class P{static void Main(){x.Write(x.In.ReadToEnd());}}

Thanks Lynn for the hint about using alias vs using static.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

pb, 20 bytes

^w[B!0]{t[B]vb[T]^>}

It will print an input prompt, but I can't do anything about it. This language has no way of supporting infinite input.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Lolo, 2 bytes

Lo

Not very interesting for a language only made up of Ls and Os.
It's basically printing whats in the stack. Since there is nothing, it gets the input.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

TCL, 28 bytes

puts -nonewline [read stdin]
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Common Lisp (Lispworks), 50 bytes

(defun f()(let((x(read-char)))(format t"~A"x)(f)))

Usage:

    CL-USER 165 > (f)
    aabbccdd

    112233

    ddeeff
| improve this answer | |
\$\endgroup\$
1
4 5
6
7 8
10

Not the answer you're looking for? Browse other questions tagged or ask your own question.