text:
I double the source, you double the output!
Your task, if you wish to accept it, is to write a program that outputs a positive integer (higher than 0). The tricky part is that if I duplicate your source code, the output must be double the original integer.
Rules

You must build a full program. That is, your output has to be printed to STDOUT.

The initial source must be at least 1 byte long.

Both the integers must be in base 10 (outputting them in any other base or with scientific notation is forbidden).

Your program must not take input (or have an unused, empty input).

Outputting the integers with trailing / leading spaces is allowed.

You may not assume a newline between copies of your source.

This is code-golf, so the shortest (original) code in each language wins!

Default Loopholes apply.

Example
Let's say your source code is ABC and its corresponding output is 4. If I write ABCABC instead and run it, the output must be 8.
Leaderboard
This uses uses @manatwork's layout.

/* Configuration */

var QUESTION_ID = 132558; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 8349457; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://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 "https://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,]*[^\s,]),.*?(-?\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 = '
' + c.body.replace(OVERRIDE_REG, '') + '
';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });

  });

  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;
    if (! /<a/.test(lang)) lang = '' + lang + '';
    lang = jQuery(lang).text().toLowerCase();

    languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link, uniq: lang};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.uniq > b.uniq) return 1;
    if (a.uniq < b.uniq) 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);
  }

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

<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/Sites/codegolf/all.css?v=617d0685f6f3">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}

{{LANGUAGE}}	{{NAME}}	{{SIZE}}

Related

Can we assume a newline between copies of the source?

@steenbergh No, you can't.

@Mr.Xcoder Then I'll just have to include one in my own source.

@Mr.Xcoder I think that you should have prevented reading your own source code.

"Both the integers must be in base 10." oh no I can't just post 1 and claim it's in unary! oh man :( D: :P

Can we assume the interpreter is reset between program runs?

@user202729 Yes, you can.

Are leading zeros allowed? E.g. there's a Hexagony solution that prints 002 and 4.

@MartinEnder Yes, that is perfectly fine.

It only needs to work when doubled once? We don't need to support n many doublings?

@CodyGray When doubled once. You have to support 1 doubling.

This challenge could be fun, if not for the The initial source must be at least 1 byte long. requirement

@Daniel Let's say your source is (empty program) and it produces `5`. If you double it, your source is (empty program) and that produces 5 as well, no matter what you do. That being said, an empty program duplicated is still the empty program, and always produces the same output, except for  the case where the empty program means something else (a random number generator, for example), which could not be valid anyway.

@Mr.Xcoder If you're so sure, why not remove the rule?

@Daniel Because I want to keep it :P

This shouldn't be hard for esolangs that automatically dump the top of stack upon program termination.

Does output have to be base 10?

@Cyoce Both the integers must be in base 10

If we have a stack based language with no implicit output, can we assume the top of the stack is output?

@Zacharý Can you give me an example?

MY. Just MY in general since it has no implicit IO. 1 would push 1 to the stack, but nothing to stdout.

@Zacharý No, sorry

Needs clarification that the output must be printed. Output doesn't necessarily mean anything visible to the end-user; for example, a function f(x){return ++x;} would output (not print) x, incremented by 1.

@Rogem You must build a full program already  implies that.

It does not - for example C allows returning an error code from a program upon program termination by returning from main().

@Rogem I have edited the challenge to address your concerns.

Can you explain "must not throw any error" rule? I'm trying to use a language which, due to syntactic quirks, would cause the interpreter to segfault at the end of the normal program (after producing the correct output), but would continue executing without error and produce the correct doubled output (and segfault at the end of that). The program would still produce the correct output, but it would segfault in both cases.

@EsolangingFruit I removed that rule. I don’t even remember why and when I added it lol ;-)

@Mr.Xcoder I've seen a few submissions using \r to override the previouly written text. Do you endorse that?

@EsolangingFruit Unfortunately, I cannot enforce them not to use it. \r is acceptable.

I hereby give 200 points of my reputation to a person completing the challenge in Malbolge.

What is the intention of Your program must not take input (or have an unused, empty input) besides excluding languages that simply can't run without at least an empty input (like sed)?

Python 2, 33 bytes
print len(open(__file__).read())#

Try it online!
Try it doubled
Python 3, 28 bytes
print(len(*open(__file__)))#

Try it online!
Try it doubled
Explanation
This opens up the source code using open(__file__) and gets its length using len the # prevents any additional code from being read.  When the source is doubled so is the length.

Wow, I'm stunned... That's so brilliant!

32 bytes. Works by using append mode, setting the current position to the end of the file. tell() returns the current position in the file

@HalvardHummel Nice.  However I have no intention of updating this answer.  If you would like to post it on your own it is substantially different in my opinion.

@WheatWizard That is understandable, I made a separate answer

Jelly, 1 byte
‘

Try it online!
or Try it double!
I have no idea how this works, but apparently it does.

That moment when you have no idea what you have written...

Darn it, I just thought of this 8 minutes too late.

All links need an argument. If the first element of the chain is a nilad, its result becomes the argument and the link is executed monadically. If there is no leading nilad, 0 is used instead.

Google Sheets, 5 Bytes
Anonymous worksheet formula that takes no input and outputs into the cell which holds the formula
=4/(2

As a single formula this evaluates to a call stack that looks a little something like
=4/(2
=4/(2)
=4/2
=2
2

However when this worksheet formula is doubled this call stack evaluates down to
=4/(2=4/(2
=4/(2=4/(2)
=4/(2=4/(2))
=4/(2=2)
=4/(True)
=4/True
=4/1
=4
4

Of course, an implication of using this method is that once this is repeated more than once, at the third and all following iterations of the problem, the call  stack will reach =4/(2=4) and thus evaluate down to =4/0 and throw a #DIV/0! error

Never expected Google Sheets would have use in code golf. Clever solution

@hucancode the really interesting bit about this is that because Excel throws an error if you exclude the trailing )'s this answer is the only Google Sheets answer that I've Seen that does not translate into an Excel answer

LibreOffice works.

C (gcc), 37 bytes
i;main(){putchar(i+49);}/*
i=1;//*///

The file does not contain a trailing newline.
Doubled version, for syntax highlighting:
i;main(){putchar(i+49);}/*
i=1;//*///i;main(){putchar(i+49);}/*
i=1;//*///

TIO links: single, double.

Can you please explain how this works? why would the comment ever be uncommented?

When you double the source code, the /* is commented out by the //, which means the following i=1 is uncommented. This is easier to see if you put the doubled version of the code in a syntax highlighter

Whoa, a tentative definition trick. Nice.

Python 2, 21 bytes
+1
if id:id=0;print 1

Try it online!
Doubled:
+1
if id:id=0;print 1+1
if id:id=0;print 1

Try it online!

Crazily creative! Congrats!

What if it is doubled with a linefeed inbetween?

05AB1E, 2 bytes
Original
XO

Try it online!
Doubled
XOXO

Try it online!
Explanation
X pushes 1 to the stack.
O sums the stack.

XOXO, nice solution.

You did that on purpose, while you knew you could've also used 1O!

Where do you guys find these ridiculous languages?

@DavidB: There are plenty of cool and interesting languages to find on TIO :)

There's also esolang.org

@DavidB Usually, they write them.

@FedericoPoloni Well if everyone writes the language on their own, these Code Golfs should all be easy for everyone.

@DavidB Yes, people do invent languages for codegolf, and yes, they can get impressively low scores, but doing silly things like inventing a language after the challenge to solve it in 1 byte are disallowed, and programming in these languages is usually far from easy.

Hexagony, 7 bytes
/)!@.).

Prints 1 regularly then 2 doubled.
Try it online! or
Try it doubled online!
Expanded versions:
Regular:
 / )
! @ .
 ) .

Doubled:
  / ) !
 @ . ) .
/ ) ! @ .
 ) . . .
  . . .

The regular program follows the path: /)!.@ which increments a memory edge (all are initialised to zero) then prints its numeric value. The doubled program follows: /.)/)!@ which increments the edge twice before printing, instead.

Wow nice work. I assume you found that by hand? Since 6 bytes is in brute force range, I thought I'd give it a go, and there's actually a 4-byte solution: [@!) (and some 570 5-byte solutions). Since you actually went to the trouble of finding a solution by hand, I'm perfectly happy for you to post the 4-byte solution.

If you're interested, here is the full list including the number that is printed: https://pastebin.com/TtRujjA4

Braingolf, 1 byte
+

Try it online!
Now we're talkin'!
Outputs 20, or 40 when source is doubled.
Explanation
+ is of course the "sum", "add" or "plus" operator, in Braingolf, however it has dyadic, monadic and niladic functions.
When there are at least 2 items on the stack, it's dyadic, and will sum the top 2 items of the stack.
When there is only 1 item on the stack, it's monadic, and will double the item.
When there are no items on the stack, it's niladic, and pushes 20!
Why does it push 20? Well because an empty Braingolf program simply prints a newline, and the ASCII value of a newline is 10, so I figured I'd make niladic + push 20 so it's like it's actually being monadic on the implicit newline (even though it isn't at all)
Therefore:
+   No input
+   Niladic sum, Push 20
    Implicit output

And when doubled up:
++  No input
+   Niladic sum, Push 20
 +  Monadic sum, Double top of stack
    Implicit output

Haskell, 26 18 bytes
main=print$0
 +1--

Try it online!
Doubled:
main=print$0
 +1--main=print$0
 +1--

Try it online!
I found this version while answering the tripple version of the challenge.

26 byte version without comment abuse:
main|n<-1,nmain<-2=print n

Try it online! Prints 1.
In the pattern guard the identifier n is set to 1 and nmain to 2, then print n prints 1.
Double program:
main|n<-1,nmain<-2=print nmain|n<-1,nmain<-2=print n

Try it online! Prints 2.
In the first pattern guard again n is set to 1 and nmain to 2, however the print statement has become print nmain, so 2 is printed. Because identifier declarations in a pattern guard evaluate to true, the second pattern guard can never be reached.

Mathematica, 5 bytes
(1+1)

outputs 2
and (1+1)(1+1) outputs 4
and of course (as many of you asked)
Mathematica, 3 bytes
(2)

Does (2) work?

@geokavel 2 and a space would work, as would +1 but it should be noted that all of these assume Mathematica's notebook environment

If you run it in the opencloud Mathematica Sandbox, a single space becomes x, such that 2  outputs 2 and 2 2  becomes 2x2  that prints 4. You can add that as an alternative solution.

(2) works as well.

2  works as well.

Brain-Flak, 6 bytes
({}())

Try it online!
Explanation
What this does should be pretty clear.  {} grabs a value from the stack, which implicitly zero to begin with,  () adds one to it and (...) pushes the value.  On the second run since there is already a 1 on the stack this just adds another 1 to it to make two.  In fact if you copy the code n times it will always output n.

><>, 7 6 bytes
-1 byte thanks to Teal pelican
\ln;
0

Try it online!
Try it doubled!
Explanation
I used a 0 but I could have also used 1-9, a-f because they all push a single value onto the stack.
Not doubled:
\ redirects execution down
0 pushes zero onto stack; STACK: [0]
  (IP wraps around the bottom)
\ redirects execution right
l pushes stack length (1) onto stack; STACK: [0, 1]
n pops off the top value (1) and prints it; STACK: [0]
; end of execution

Doubled:
\ redirects execution down
0 pushes zero onto stack; STACK: [0]
0 pushes zero onto stack; STACK: [0, 0]
  (IP wraps around the bottom)
\ redirects execution right
l pushes stack length (2) onto stack; STACK: [0, 0, 2]
n pops off the top value (2) and prints it; STACK: [0, 0]
; end of execution

Welcome to PPCG! This is a great first answer, with a very well thought explanation and good code. You earned my upvote!

I've just seen this answer and it's great! Very nice improvement on the couple ><> answers (including mine!) - Have a look at the TIO link here; https://tio.run/##S8sszvj/PyYnz5rLAEL@/w8A - All I've done is move the 0 to the space and it saves 1 byte. :)

@Tealpelican Thanks! I can't believe I missed such a simple improvement. (Actually I can, I don't use ><> very much and I'm new to golfing!)To be honest, I didn't really look at the other solutions in detail, I saw they were relatively large and decided to try golfing the problem since it would be easier to compete.

Nice answer! Just wanted to point out that this uses the same method as my Klein answer.  (Not accusing you of copying me If anyone was that just pointing out two similar answers.)

Python REPL, 2 bytes
Also works in Pip, Dyalog APL, JavaScript REPL, J, and R
+1

I'm making a TIO right now I couldn't get python repl to work on TIO

+1 is exactly what I will do :P but darn, you ninja'd me by about a minute ><

This also works in Dyalog APL.

Polygolt

Couldn't you use this and this for a REPL?

also works in JS(paste it into the console)

You have my +1.

Also works in J and R

To be clear, it works in some JavaScript REPLs, it's not "a complete program" as requested.

Also works in WolframAlpha, which is not a programming language

JavaScript, 38 bytes

setTimeout('alert(i)',i=1)/*
i++//*///

setTimeout('alert(i)',i=1)/*
i++//*///setTimeout('alert(i)',i=1)/*
i++//*///

Nice one! Could you just do i++?

@Arnauld: indeed, thanks for the suggestion!

Retina, 3 bytes

1

Try it online!
Prints 2. Doubling it prints 4.
The 1 can be replaced with pretty much anything else.
Explanation

1

Replaces the empty input with 1.

Counts the number of empty matches in 1 which is two (one before the 1 and one after it).
If we double the program, we get an additional stage like the first one. This time it inserts a 1 before and after the initial one, giving 111. When we now count the number of matches of the empty regex we get four of them.

Java8, 135 118 110 bytes
Single, prints 8
interface T{static void main(String[]a){System.out.print(Byte.SIZE);}}/*
class Byte{static int SIZE=16;}/**///

Doubled, prints 16
interface T{static void main(String[]a){System.out.print(Byte.SIZE);}}/*
class Byte{static int SIZE=16;}/**///interface T{static void main(String[]a){System.out.print(Byte.SIZE);}}/*
class Byte{static int SIZE=16;}/**///

Previews answer, 118 bytes
Single, prints 1
interface T{static void main(String[]a){System.out.print(T.class.getResource("B.class")==null?1:2);}}/*
enum B{}/**///

Doubled, prints 2
interface T{static void main(String[]a){System.out.print(T.class.getResource("B.class")==null?1:2);}}/*
enum B{}/**///interface T{static void main(String[]a){System.out.print(T.class.getResource("B.class")==null?1:2);}}/*
enum B{}/**///

How this works
The java-compiler creates a single file for every class in the source file.
Therefore i can simply check if a resource with the name B.class exists.

Orginal Answer, 135 bytes
Single, prints 1
interface T{static void main(String[]a){int i=1;try{Class.forName("B");i=2;}catch(Exception e){}System.out.print(i);}}/*
enum B{}/**///

Doubled, prints 2
interface T{static void main(String[]a){int i=1;try{Class.forName("B");i=2;}catch(Exception e){}System.out.print(i);}}/*
enum B{}/**///interface T{static void main(String[]a){int i=1;try{Class.forName("B");i=2;}catch(Exception e){}System.out.print(i);}}/*
enum B{}/**///

What you did with the comment is really cool. But do you really need the new line?

Oh nvm, didn't notice the single line comment on second line

Python 2, 32 bytes
print open(__file__,"a").tell()#

Try it online!
Double source code
Explanation
This opens the source code file in append mode
open(__file__,"a")
We then find the current position in the file, this will be at the end of the file due to opening in append mode
open(__file__,"a").tell()
We print this length
print open(__file__,"a").tell()
And add a comment, so that doubling the source code does not execute more code
print open(__file__,"a").tell()#

Neim, 1 byte
>

Simply increments the top of the stack.
The stack can be imagined as an infinite amount of zeroes to start off, so this increments zero to get one, and doubled, increments it again to get two.
Try it online!
An alternative solution:
ᛖ

Adds 2, instead of 1.

Excel VBA, 12 Bytes
Anonymous VBE immediate window function that takes input from and outputs to range [A1]. The default value of the range [A1] is "" (empty string) and after one execution the following sets this to 1 and increments by 1 with all subsequent executions.
[A1]=[A1+1]:

Input / Output
Single Version
[A1]=[A1+1]:
?[A1]    ''# display the value of [A1] to the VBE immediate window
 1

Doubled Version
[A1]=[A1+1]:[A1]=[A1+1]:
?[A1]    ''# display the value of [A1] to the VBE immediate window
 2

Japt, 1 byte
Ä

Try it online!
Try it doubled!
Repeats even longer, too!
Rather simple. Japt transpiles to JS, and Ä transpiles to + 1, so ÄÄ transpiles to + 1 + 1, and so on.

I was just about to post the same thing with É - luckily I scanned the answers first.

Husk, 3 bytes
|1"

Try it online!
An original idea, for what I have seen in other answers.
Explanation
| in Husk is an "or" operator which returns its second argument if it is thruthy, otherwise the first argument. When applied to arguments of different types it firstly transform all of them into numbers: the transformation for strings (and lists in general) is done by computing their length.
In the original program we apply | to 1 and an empty string, which gets converted to 0: the result is 1.
In the doubled program we apply | to 1 and the string "|1", which gets converted to 2: the result is 2.

SHENZHEN I/O Assembly, 35 19 bytes, 3¥
-16 bytes, thanks @l4m2!
@add 7
@mov acc x1

Ooh, nice to see Shenzhen I/O here.

Why not just @add 7/@mov acc x1?

@l4m2 huh, I don't know. Seems like that would work.

CJam, 3 bytes
5],

Try it Online
Encapsulate 5 in array. Return length of array. When you duplicate code, the previously returned length, 1, is already on the stack, so you get an array of [1,5], which returns length 2.

Ruby, 16 bytes
+1
p&&exit
p=p 1

Try it online!
Doubled:
+1
p&&exit
p=p 1+1
p&&exit
p=p 1

Try it online!Try it online!

Braingolf, 1 byte
+

Try it online!
Try it doubled!
I don't know how this works, most important it does!

As far as I can see, this is a late duplicate of the well explained https://codegolf.stackexchange.com/a/132573/72726, so this can be deleted.

@Philippos Duplicate answers are allowed

Befunge-98, 5 bytes
90g.@

Try it online!
g gets the character value at coordinate (9, 0) in Funge-Space; . prints it as an integer, and @ halts the program. In the un-doubled version, (9, 0) is out of bounds of the program, and Funge-Space outside the program is initialized to the default value of a space, so we print 32. In the doubled version, (9, 0) is the @ character, so we print 64.

This was not what i expected the best Befunge-98 answer to look like... really creative answer!

I spoke too soon ;)

Wumpus, 4 bytes
" O@

Try it online!
" O@" O@

Try it online!
The normal code prints 32 and the doubled one prints 64.
Explanation
" works like it does in many other Fungeoids: it toggles string mode, where each individual character code is pushed to the stack, instead of executing the command. However, in contrast to most other Fungeoids, Wumpus's playfield doesn't wrap around, so the IP will instead reflect off the end and bounce back and forth through the code.
So for the single program, the following code is actually executed:
" O@O " O@

The string pushes 32, 79, 64, 79, 32. Then the space does nothing, the O prints 32, and the @ terminates the program.
For the doubled program, the string is instead terminated before the IP bounces back, so the code is only traversed once:
" O@" O@

This time, the string pushes 32, 79, 64, the O prints the 64 and the @ terminates the program.
This appears to be the only 4-byte solution.

SOGL V0.12, 1 byte
I

Try it Here!, or try the duplicated version
I is the increase command, and as no input is provided, it increases 0 (and then in the duplicated program, 1 to 2)

Can you provide a working link for me to test it on my mac as well (the classic problem)? EDIT: Thanks.

,,,, 2 bytes
1∑

Explanation
1∑

1   push 1
 ∑  pop everything and push the sum of the stack

Am I missing something or wouldn't that be 3 for a doubled source code?

@TaylorScott I'm sorry, I should've noted that ∑ pops all of the elements on the stack.

That makes much more sense - thanks for the clarification

Sigma is two bytes, no?

@nishantjr ,,, uses its own code page, which is linked in the header.

JavaScript (ES6), 63 bytes
Prints either 1 or 2 through an alert dialog.
Original

clearTimeout((t=this).x),t.x=setTimeout(`alert(${t.n=-~t.n})`);

Doubled

clearTimeout((t=this).x),t.x=setTimeout(`alert(${t.n=-~t.n})`);clearTimeout((t=this).x),t.x=setTimeout(`alert(${t.n=-~t.n})`);

I guess this would work also: window.i=++window.i||1; in the browser console. It ouputs 1. Browser refresh, window.i=++window.i||1;window.i=++window.i||1; ouputs 2.

@ChristiaanWesterbeek True. But then it's a REPL answer (and you can actually just do this.i=++this.i||1;).

I don't know what that means, REPL answer

@ChristiaanWesterbeek REPL stands for Read-Eval-Print Loop. In that case, the final result is not explicitly printed by the code but by the shell it's running in (like the browser console).

@ChristiaanWesterbeek (Actually, just +1 would work in REPL -- like this Python REPL answer does.)

Of course... As you might have guessed, I'm relatively new here at codegolf. Where or how does the question exclude REPL answers? To another answer I've written, it was commented that even a resolved promise counts as output. or maybe you meant it's not excluded, but just boring :)

@ChristiaanWesterbeek The question does not exclude REPL answers, but there was little point in adding another one after the Python one was posted.

Batch, 13 bytes
@echo %~z0
:

Explanation: %~z0 expands to the length of the source file, so doubling the file simply doubles the length. The second line defines an empty label, which does nothing. When the file is doubled, it becomes a label named @echo %~z0 instead, while the third line is another empty label.

QBasic,  44  28 bytes
There is no newline at the end. Outputs 4 when single, 8 when doubled.
4
READ x,y
?x+y
END
DATA 4,0

Explanation
For the single version:

4 is a line number.
READ x,y takes the first two values from the DATA statement and stores them in x and y. Thus, x gets 4 and y gets 0.
?x+y adds the two numbers and prints them.
END exits the program.

In the doubled version, the DATA statement becomes DATA 4,04, which assigns 4 to both x and y, thus making x+y equal 8 instead.

Python, 15 bytes
1or exit(2)
0/0

Outputs via exit code.  Divides by zero and exits with code 1.  Doubled:
1or exit(2)
0/01or exit(2)
0/0

Calls exit(2) and exits with code 2.
Python?, 9 bytes
';exit(2)

Throws a syntax error and exits with code 1.  Doubled:
';exit(2)';exit(2)

Calls exit(2) and exits with code 2.

Befunge-98 (PyFunge), 3 bytes
This answer draws heavy inspiration from this one, go vote them up too!
".@

Try it online! or Try it online doubled!
Explanation
When wrapping back around to the beginning of the source in quote mode, this Befunge-98 interpreter pushes at least 1 space (ASCII 32). If we print this value and exit, we get 32.
If we double the source code, we don't wrap back around, but rather end quote mode with the duplicated ". This means that the last character pushed is not a space, but a @, with (drumroll) ASCII 64! A complete coincidence that the character that ends the program in Befunge is twice that of a space.

Perl 5, 7 bytes
With -M5.10.0
say
+1#

Try it online!
Doubled:
say
+1#say
+1

-2 thanks to Ton Hospel

Use say to gain 2 more bytes (The -M5.10.0 or -E instead of -e is free)

PHP, 30 bytes
Original

<?=strlen(file(__FILE__)[0]);#

Try it online!
PHP, 60 bytes
doubled

<?=strlen(file(__FILE__)[0]);#<?=strlen(file(__FILE__)[0]);#

Try it online!

Port of the Python solution?

@Mr.Xcoder after your comment I have saw the python solution. It is the same way

Why not <?=strlen(file(__FILE__)[0]);#

@DarrenH I have not thinking about it

this is 23 bytes: <?=filesize(__FILE__);# - and doubled is 46 bytes.

J, 2 bytes
+1

+1 is 1, and +1+1 is 2.
Fun fact: since J's operator precedence is just right-to-left, this is interpreted as +(1+1)

This is a real Polyglot: Python REPL, APL, J, Pip

@Mr.Xcoder To be fair it works in pretty much every non-esoteric language with a REPL.

I thought J's operator precedence was right to left? e.g. 3*6+5 = 33

@RichardDonovan right. I goofed

Hexagony, 4 bytes
[@!)

Try it online! or
Try it doubled online!
This solution was found using brute force by Martin and prints 002 regularly and 4 when doubled. This is the only 4 byte solution, but there are several hundred 5 byte solutions.
Expanded versions:
Regular:
 [ @
! ) .
 . .

Doubled:
  [ @ !
 ) [ @ !
) . . . .
 . . . .
  . . .

Hexagony has 6 instruction pointers, one starting at each corner of the hexagon and initially moving "clockwise." The [ instruction causes the interpreter to change IP one left. The first program leads us on a bit of a merry go around, executing: [![.!.)[...)!@ which results in the 002 output. The other program is a bit more tame, executing: [))[..)...[.......)!@ which results in the clean 4.

JavaScript (REPL), 2 bytes
So long as putting code in the console counts as a full program:
+1

Putting the code in the console does not count as a full program. This is a snippet and therefore, unfortunatly, invalid.

Even if I make as REPL?

I'd say mark it as REPL and run with it. People who have sour grapes over "JavaScript REPL" but not over the various golfing languages which get such things down to one byte are being oddly specific with their moralistic tendencies. The interpreter which runs JS REPL code is a lot more straightforward than, say, Bubblegum.

Marked as REPL.

Google Sheets / Excel, 2 Bytes
The Trival Solution
+7

Or
+n

Such that n is an integer between 1 and 9, inclusive.
Google Sheets and Excel both will take a leading + or - and evaluate them down to = or =-, respectively if they are the leading character of a cells formula text. As a result, -n, such that n is an integer between 1 and 9, inclusive, is a valid negative equivalent of the above
As a single formula this evaluates to a call stack that looks a little something like
+7
=7
7

However when this worksheet formula is doubled this call stack evaluates down to
+7+7
=7+7
=14

Whispers v2, 23 bytes
+1
> 1
>> Output 3
>> 1

Try it online! or Try it online doubled
Outputs 1 normally and 2 when doubled.
How it works
Normal
Whispers only recognises lines that match one of a certain set of regexes. In the normal version, this reduces the program down to
> 1
>> Output 3

(i.e. the first and last lines don't match any regexes). The program then runs the last line, >> Output 3. This calls the 3rd line and outputs the result. However, as the reduced program only has 2 lines, this indexes modularly, returning the \$3 \mod 2\$th line (i.e. the first line), > 1. This is a basic nilad line which returns \$1\$, which is then outputted.
Doubled
The doubled program is
+1
> 1
>> Output 3
>> 1+1
> 1
>> Output 3
>> 1

Removing lines which don't match any regex, we get
> 1
>> Output 3
>> 1+1
> 1
>> Output 3

Again, the last line is run, telling the program to output the result of line 3. This time however, we do have a line 3 to output: >> 1+1. This does return \$2\$ but not because it evaluates \$1+1\$. Rather, it adds the value of line 1 to itself, which happens to be \$1\$.
Interestingly, this means that by changing > 1 to > n where \$n\$ is any number, the programs output \$n\$ and \$2n\$. For example
+1
> π
>> Output 3
>> 1

outputs \$\pi\$ normally or \$2\pi\$ when doubled

vJASS (Warcraft 3), 150 bytes
//! inject main
set bj_randDistCount=bj_randDistCount+1
call ClearTextMessages()
call BJDebugMsg(I2S(bj_randDistCount))
//! dovjassinit
//! endinject

prints 1
//! inject main
set bj_randDistCount=bj_randDistCount+1
call ClearTextMessages()
call BJDebugMsg(I2S(bj_randDistCount))
//! dovjassinit
//! endinject
//! inject main
set bj_randDistCount=bj_randDistCount+1
call ClearTextMessages()
call BJDebugMsg(I2S(bj_randDistCount))
//! dovjassinit
//! endinject

prints 2
Explanation:

bj_randDistCount is a non-constant integer variable. Also, it has the shortest variable name you may find in blizzard.j.
ClearTextMessages() clears all text messages in your in-game screen.
I2S(int whichInt) -> string converts from integer to string
BJDebugMsg(string str) prints text on your in-game screen.

Pyth, 3 bytes
s[1

sums a list
Try it!
Double-try it

Charcoal, 7 bytes
ＰＩＬ⊞Ｏυω

Try it online! Appends the empty string to the empty list and prints the length of the result (1) in decimal without moving the cursor. When doubled, the empty string gets appended twice so the length is now 2, which then overwrites the 1. Try it online! In verbose syntax, this is Multiprint(Cast(Length(PushOperator(u, w))));.

When I look at the code, it looks like it says "pillow"!

Self-modifying Brainfuck, 7 bytes
<-<201/

or doubled:
<-<201/<-<201/

Outputs 1 and 2 respectively.
The idea is simple: we use Self-modifying Brainfuck's self-modifying capability to make sure that the printing command only happens at the end of the full program.
Try it online!
Try it online, doubled!

bash, 16 bytes
a simple one:
wc -c<$0;exit 0;

First program: Try it online!
Second program: Try it online!

Thanks @Step-hen for the 2 TIO, I tried to use the site myself while writing the answer, but nothing happened when I pressed the run button (no output on my own attempts to set it up... weird as it was identical to yours...). Thanks for putting those 2 working links.

No problem, I believe something is going wonky with TIO's backend right now (Dennis was talking about DOS attempts) so it's working on and off, sometimes it acts like it is infinitely looping.

@StepHen: this looks like what was happening to me indeed (play button was looping). Thanks fo the info. Maybe not a DOS but just someone putting a script there that requires too much processing power? (Hanlon's razor : "Never attribute to malice that which is adequately explained by stupidity" ^^ )

wc is not part of bash, so should be mentioned in the title line. And I see no bashism so think, this will run on sh+wc too.

This for 10 bytes.

Little Man Computer, 20 bytes (source)
LDA 1
ADD 5
OUT
HLT

Online Emulator (Flash)

Wowee never thought i'd have to see LMC again after I finished my a levels ... lovely little answer

Python 2, 24 bytes
'+1#';exec'print 1''' ''

Abusing string syntax.

Powershell, 2 bytes
+1

It's a full Powershell program. The output has printed to STDOUT.

Python 2, 27 bytes
+7
try:_
except:_=7;print _

Try it online!
Try it doubled!

Brachylog, 8 bytes
w₆-₇ℕ~l"

Try it online! Try it online!Try it online!
Although Brachylog has implicit function output, full programs won't automatically print without being given arguments, making this challenge a bit more interesting.
w₆          Declaratively write a number
  -₇        which minus 7
    ℕ       is a whole number (so length won't throw an error)
     ~l     equal to the length of
       "    an (implicitly terminated) empty string.

Doubling the code turns the empty string into a string of length 7, changing the printed output from 7 to 14.

K (ngn/k), 3 bytes
+/1

Try it online!

+/1 - sum 1. returns 1
+/1+/1 - rightmost +/1 evaluates to 1 (as above), giving +/1 1, i.e. sum the vector 1 1. returns 2
EDIT: above is incorrect (written when i had a bad understanding of how k is parsed). corrected explanation:
+/1+/1 is +/(1+/1), where the parenthesized expression is "sum 1 with a seed of 1", which evaluates to 2, which is passed to +/, returning 2

Vyxal, 1 byte
›

Try it Online!
Doubled:
››

Try it Online! Try it Online!
Increments the top of the stack. Since the stack is empty, 0 is incremented instead, outputting 1. When doubled, 0 is incremented twice, outputting 2.

V, 4 bytes
øß.

Try it online!
Or Try it doubled!

Cubix, 6 bytes
@1u.2O

When run, this pushes 1, u-turns, Outputs as a number, and h@lts:
  @
1 u . 2
  O

When doubled, the cube is
    @ 1
    u .
2 O @ 1 u . 2 O
. . . . . . . .
    . .
    . .

which simply pushes 2, Outputs as a number, and h@lts.
Try it online!

While looking at the duplicate question for a bit of fun I came up with this ^5O@N.  Also has the twist of printing out it's length :)

@MickyT you should post that as your own answer! That's a super cool one :)

Done, but found another byte which made it a bit more boring

Ruby (REPL), 3 2 bytes
Must be run interactively for the implicit output:
+2

Outputs 2.
Doubled:
+2+2

Outputs 4.
2 and 4 are more interesting than 1 and 2

@MorganThrapp REPL answers are allowed, as long as they're clearly labeled as such.

My bad. I haven't been actively recently and missed that.

+2 is a byte shorter.

R, 2 bytes
+1

prints 1 and when doubled
+1+1

prints 2

or +T or +2 or...

This is exactly the same as the J answer.

C++, 158 138 123 bytes
20 byte savings thanks to @zbw
I'm sure there's a more efficient way to do it in C++ but this is all I could think of.
#include <iostream>
#ifdef m
#define m a r;
#else
int v;
#define m struct a{a(){++v;}}q;int main(){std::cout<<v;}
#endif
m

How it works: On the first instance, it declares a global int v initialized to 0 and a struct a which increments every time an a is instanced. It instances an a, and prints the value of the member.
On the second instance of the source, it just instances another a.

You could change a to a struct, where it'll default to public, saving 6 bytes (explanation here).  Also, remove the unneeded #undef, for 9 bytes, and reorder the cases in the #ifndef so it becomes #ifdef for another.  You can remove the int  before main. Try it online!

@zbw Good catches! Thanks. (Can't believe I forgot the struct thing in particular.) The #undef was to avoid a compiler warning but I guess that's not an issue for code golf. :)

PHP, 16 bytes
Does not actually satisfy the rules because of PHP warnings.
ob_start(bcadd);

Test it online.

Not really 16 bytes as you need to turn errors off to pass OP's rules

And if you include the tags, opening and closing because you cannot double the source without the closing tag, it comes in at 61 bytes. http://sandbox.onlinephpfunctions.com/code/6909403a14f65dffef3238e0ec87dfaa67ced6c6 ! Quite far from 16!!

The OP’s rules actually say that warnings are OK, BUT, strangely, and I don't understand what's going on here, if the warnings are not turned off then the single code and the doubled code both return 9, and so the warnings are an essential part of your code. The shortest I can get your script down to is 56 bytes (http://sandbox.onlinephpfunctions.com/code/f861d4f7fe8163df11f35e45a8429b6283145f5c), 40 more than the 16 you are falsely claiming. How about changing your answer?

Fourier, 3 bytes
@^o

Try it Online!
Try it Doubled!
Explanation:
Undoubled:
@    - Clear screen
 ^   - Increment the accumulator (initialised to zero)
  o  - Output the value of the accumulator

Doubled:
@       - Clear screen
 ^      - Increment the accumulator (initialised to zero)
  o     - Output the value of the accumulator
   @    - Clear screen
    ^   - Increment the accumulator
     o  - Output the value of the accumulator

Python 3, 33 bytes
Cheating a little:
id=print('\r',1+(not id),end='');

On a full console, you should only see 1 or 2; or did you mean that the whole output stream contains more than the number itself? (I'm not sure how this behaves in Windows, but on Debian or a Mac, this looks like a single output).

Oh, yeah, I did a test in TIO before and saw that it didn't work there. In a console, the \r gives a carriage return, but not a newline. Thus, when the second copy of the code is run, it actually starts overwriting the content from the first copy of the code.

R, 2 bytes
+T

Never expected to codegolf this much in R.
Due to the +, R changes the T for a numeric, using 1 as default.

PHP, 26 bytes
<?=ob_clean()+ob_start()?>

Try it online!
Try it doubled!
Explanation
PHP can use an output buffer. This buffer has the facility to be cleaned without its contents ever being sent.
When the script is run just once, the output buffer has not initially been started and so cannot be cleaned, and ob_clean() returns false. The buffer is then successfully started and ob_start() returns true. false + true is really 0 + 1, and so the script echoes 1 into the buffer and ends with the buffer being outputted.
If the script is doubled then this first 1 is not output but is still in the buffer when the second half of the doubled code starts. The output buffer is now cleaned, the 1 is lost, and ob_clean() this time returns true. Another output buffer is then started (they are, in fact, stacked) and ob_start() again returns true, so this time we have true + true, which is 1 + 1, and so 2 is sent to the output buffer and then on to the actual output when the script ends.

Proton, 63 53 52 bytes
+(x? !print(x=2):0)
while(x? x-2? print(1):0:(x=1))x

Prints 1.
Try it online!
Doubled:
+(x? !print(x=2):0)
while(x? x-2? 0:print(1):(x=1))x+(x? !print(x=2):0)
while(x? x-2? 0:print(1):(x=1))x

Prints 2.
Try it online!

Removing the spaces seems to give the desired results

Rust, 62 bytes
fn main(){let a=include_str!("a.");print!("{}",a.len()-1)}//

What's happening is the file is including itself as a string during compiletime, and getting the length of itself.
When appended, the extra code is commented out, but still effects the length of the file.
Only works if the file name is 'a.'
Secondary Solution, 63 bytes
fn main(){let a=include_str!(file!());print!("{}",a.len()-1)}//

This solution doesn't use a hardcoded filename, losing 1 byte.

If the file name is needed, then you have to add the file name to the bytecount. Meta post

Done. I still gain a byte. ^_^ (I'd remove the dot, but otherwise rustc complains)

Underload, 15 13 8 bytes
-2 thanks to Martin Ender
-5 thanks to Ørjan Johansen
(1)\r2)S(

The \r in the code should be a literal carriage return character.
There's no way for spec-complaint Underload to actually solve this challenge. This submission uses several tricks to do it:

stringie, the TIO interpreter, ignores unmatched close brackets and segfaults on unmatched open brackets, which is allowed.
Using \r allows us to overwrite whatever has already been output with new output. This requires a terminal for which \r clears the line, rather than just allowing it to be overwritten with new text.

bash builtins only - 21 bytes
The X file:
trap "echo $[++i]" 0;

EXIT –> 0
$((...)) -> $[...]
;-)

bash builtins only - 26 bytes
Straight forward while using only bash builtins.
IOW: No external helpers.
The X file:
trap "echo $((++i))" exit;

(No final newline.)
Proof of the pudding:
$ bash <(cat X)
1
$ bash <(cat X X)
2
$ bash <(cat X X X)
3

Concat with or without newline inbetween:
$ cat X X ; echo # added echo compensates missing \n only
trap "echo $((++i))" exit;trap "echo $((++i))" exit;
$ bash <(cat X X)
2
$ cat X <(echo) X ; echo
trap "echo $((++i))" exit;
trap "echo $((++i))" exit;
$ bash <(cat X <(echo) X)
2

Implicit, 2 1 byte
-1 thanks to ASCII-only
.

:)

Link's broken for me

@AidanF.Pierce fixed.

. seems to work?

Keg, 2 bytes
This indeed works. (Works in the old TIO version, I don't know which version is this)
1+

A version that I can understand, 4 bytes
1(+)

Explanation:
1#    Push 1 onto the stack
 (+)# Add the whole stack together

This probably has something to do with why it works. I can't quite tell what the stack is doing, though, because TIO seems to be running an older and significantly different version of Keg.py where line 67 is return self.content.pop().

@UnrelatedString, I haven't asked Dennis to update Keg on TIO yet because we're still testing to see that I haven't broken everything by implementing functions

Polyglot with Vyxal.

GAS x64 Assembly (Linux, GCC 10.1): 143 107 104 100 bytes
Assembled with -no-pie -nostdlib.
Original code
lea a,%rsi
lea 2,%dx
lea 1,%di
lea 1,%ax
syscall
.ifndef b
ja b
.endif
a=.
.ascii " 1\b2"
a=a+2
b=.;

Annotated Single
Single one segfaults, printing 1 to the terminal with a leading space. (Rules say this is OK.)
// Print 2 characters from a
// Use lea so we don't need $.
// We are optimizing for assembly, not machine code
lea a,%rsi
lea 2,%dx
lea 1,%di
lea 1,%ax
syscall

// Since b hasn't been defined yet, this gets left in, jumping to b
// (Pseudo-op is needed when we double)
.ifndef b
// Since gcc clears all flags at the start
ja b
.endif

// You can define re-writable labels like this too!
a=.
.asciz " 1\b2"

// Increase a by 2 (needed in double version)
a=a+2

// Attempt to jump here, but crash because there's no executable code
// Also, intentional semicolon to separate double version
b=.;

// Let crash

Gives the following:
 1[1]    74584 segmentation fault (core dumped)  ./a.out

The first 1 is the program output. Since Segfault stuff isn't program output, we're good.
Annotated Double (fluff removed)
Takes advantage of the backspace character, overwriting the 1 with a 2. (Also segfaults)
// Print 2 characters
lea a,%rsi
lea 2,%dx
lea 1,%di
lea 1,%ax
syscall

// Skip to b
ja b

// Every reference to a prior to this line points here
a=.
.ascii " 1\b2"
// Now point a to \b for next usage
a=a+2

// Now print the last two characters from new a
b=.
lea a,%rsi
lea 2,%dx
lea 1,%di
lea 1,%ax
syscall

// Crash

 2[1]    391605 segmentation fault (core dumped)  ./a.out

Before trying to improve this: Don't get confused between ASCII '1' and byte 0x1. This is very easy to do when you're dealing with low-level. ASCII '1' is 0x31 or 49, which none of these instructions or operands will assemble to in bytecode.

Flurry, 6 bytes
([])[]

Verification
$ echo -n "([])[]" | wc -c
6
$ ./flurry -nin -c "([])[]"
1
$ ./flurry -nin -c "([])[]([])[]"
2

Found by accident (kind of). Single copy returns 1, two copies returns 2.
(...) pushes its content to the stack, and [] evaluates to the stack height in Church numeral. Juxtaposition is function application (which is reversed exponentiation for Church numerals), so the entire code evaluates like the following:
Single copy
([])    Evaluate to stack height (0), and push 0 to the stack
[]      Evaluate to stack height (1)
        Function application gives 1 ** 0 = 1

Two copies
([])[]  Evaluate as above; evaluates to 1 and pushes a 0
([])    Evaluate to stack height (1), and push 1 to the stack
        Function application gives 1 ** 1 = 1
[]      Evaluate to stack height (2)
        Function application gives 2 ** 1 = 2

Honorable mention goes to the literal 2:
Flurry, 10 bytes
{<({}){}>}

Returns 2 as-is, and returns 4 (= 2**2) when doubled.
I call it a "literal" because it is a single pure {...} node (so it can be placed in larger programs without modification), and any number constant can be constructed using the same pattern.
{       Start a lambda; implicitly pushes its argument before running
 <      Start a function composition group
  ({})  Pop the argument {} and push again (...)
  {}    Pop the argument again
 >      End composition group
}       End lambda

Evaluates to the following lambda function
\f. f ∘ f
= \f. \x. f (f x)
= 2

To create a higher number n, we can place n-1 copies of ({}) before {}, which then evaluates to \f. f ∘ f ∘ ... ∘ f (n copies), which is precisely n in Church numeral. For example, 3 can be written as {<({})({}){}>}, which is similar to what I previously used.

Add++, 11 bytes
o
+1
o:""
o

Try it online!
The variable o isn't used, so the program is essentially equal to:
o
+1
o

All you need to know is that o outputs the active variable, which starts at 0, and that +1 increments the active variable. This program is equivalent to this one.
Doubled
o
+1
o:""
oo
+1
o:""
o

Try it online!
o is an empty string, so we can disregard the oo. The o variable isn't used anywhere else, so we can ignore those, and we get this program:
o
+1
+1
o

This program is equivalent to this one.

x86 Linux machine code, 16 15 bytes
XX is a linker placeholder for 15 bytes past the first instruction. It can still be repeated.
Place it in its own write+execute section.
00000034: 04 04 b9 XX XX XX XX 80 01 34 43 42 cd 80 cc     .........4CB...

        // We modify bytes "in" this section
        .section ".wtext","awx",%progbits
        .intel_syntax noprefix
        .globl _start
_start:
       // Assumes the default Linux startup state,
       // where all regs except ESP are zero.
       // EAX = 4
       // This is encoded as 04 04, which is important.
       add     al, 4
       // Set ECX to point to....nothing?
       mov     ecx, offset 1f
       // Add '4' into.... nothing?
       add     byte ptr [ecx], '4'
       // EBX = 1
       inc     ebx
       // EDX = 1
       inc     edx
       // write(1, 2f, 1)
       int     0x80
       // Exit by raising a SIGTRAP (#BP).
       // We must exit: if we double the program, it will run twice.
       int3
1:
       // Nothing

This abuses the Linux program startup state where all registers are zero, and how it doesn't get mad if you read or write a few bytes past the end of a section.
Specifically, Linux will zero pad the section to a page boundary. It doesn't care about it until you go too far out of bounds.
So label 2 when we only have one copy is this:
2:
       .byte 0x00

But when we double the code, we have this:
2:
       add     al, 4

Let's expand the encoding:
2:
       .byte   0x04, 0x04

So, when we have one copy, it is 0, and when we double it, we get 4. So all we have to do is add ASCII 4 to get '4' on a single and '8' on double.
Try it online! (Single)
Try it online! (Double)

Only one 04 used, why not place at end of program?

Desmos, 3 bytes
Original
1+0

Doubled
1+01+0

Try It On Desmos!

Any answer in the form a+0, where a is a positive integer, will work. For example, 4444+0 outputs 4444 and 4444+04444+0 outputs 8888.

Wolfram Language (Mathematica), 13 bytes
There is already another Mathematica answer, but this one is a full program instead of an REPL snippet.
Print@Depth@a

Try it online!
The depth of the expression a is 1.
Doubled:
Print@Depth@aPrint@Depth@a

Try it online!
aPrint@Depth@a is aPrint[1], which has depth 2.

K (ngn/k), 2 bytes
#2

Try it online!
#2: length of 2, which is 1
#2#2: length of two copies of 2, which is 2
This solution polyglots with J. Try it online!

Python 3, 74 67 57 bytes
Quick and dirty... Output via text file is allowed per meta.
try:f+=[2]
except:f=[2]
open('o','w').write(str(sum(f)))

f.append(2) can be f+=[2] and try: f can be try:f and except: f=[] can be except:f=[]

@Dennis happier with this version?

Much better. You need to count a trailing newline though, as open... and try... mustn't wind up on the same line.

The rules allow assuming a trailing newline between copies.

@zbw the rules say explicitly the opposite of that

@TaylorScott Oh, sorry, just re-read the rules, must've missed the "not" the first time... oh well, no worries.

Klein, 5 + 3 = 8  bytes
\+@
2

Single, Double
The single program puts a two on the stack and attempts to add it.  There is nothing to add so it is a noop and outputs 2.  In the doubled program the \+@ section is not encountered but we do hit an additional 2 meaning that when we add again we add two 2s instead of a 2 and a zero.  This results in 4.  2 can be replaced with any single digit number and this will still work, + can also be replaced with a * as long as we keep the 2, and \ can be replaced with a /.

Bash + coreutils, 43 bytes
x=$(history|cut -c 8-|tail -1);echo ${#x};#

Explanation
Outputs the length of the last command entered. Uses the same concept as the Python and PHP solutions to prevent execution of any further copies (finishes with a comment marker, so anything after it is ignored). Length of the command will be doubled when it is written twice, hence the output.

Can't you simplify this to echo ${#0};#?

i dont know about the above comment, but tail -n 1   can be shortened to tail -1

@Neil I tried that but echo ${#0};# outputs 4 and echo ${#0};#echo ${#0};# also outputs 4

@Blauhirn nicely spotted, thank you

Ah, then I misunderstood what's going on, sorry. How about wc -c $0;#?

@Neil That would output the filename next to the count. You need to use a pipe like wc -c <$0 #

><>, 24 20 bytes
\0r+n;
"

"
0
8
p
1

Try it online!
Uses the same trickery as my original 24 byte answer, just outputs 1 and 2 instead of 2/4.

\0r+n;
"

"
0
a
p
1
1
+

Try it online!
And try the double!
This starts at the \, diverts code execution down, does its trick*, pushes two 1's, then wraps around again. It hits the \ again, but from a different angle now, so the 0r+n gets executed and ; terminates the program.
(*) Note that the trick is to alter the source code by turning the instruction at 0, 10 into a space instead of a \ when the code is doubled.
When the code hits n; (print number and quit), the top of the stack is either 2 or 2, 2. In each case, a 2 gets printed, So we need to add 2 and 2 in case of the double source code, but we don't have a second stack item on the regular run. This is solved by 0r: push a zero and reverse stack. We now either sum 2 and 2 and ignore the (now bottom) 0, or we add 2 and 0.

Common Lisp REPL, 25 bytes
(if(boundp'z)6(setq z 3))

Try it online!
Try the double version online!

The rule says "to be full program"... wait that's REPL.

PowerShell, 47 bytes
(gc $MyInvocation.MyCommand.Definition).Length#

Try it online! (Output: 47)
Output:
47

Explanation
(gc $MyInvocation.MyCommand.Definition).Length#
 ^  ^             ^         ^           ^     ^^
 |  |             |         |           |     ||
 |  |             |         |           |     |No newline and/or whitespace at the end
 |  |             |         |           |     |
 |  |             |         |           |     Hash - Marks all next text as comment
 |  |             |         |           |
 |  |             |         |           Length - Returns length of string
 |  |             |         |
 |  |             |         Definition - Returns full path to script file
 |  |             |
 |  |             MyCommand - Contains information about the script file
 |  |
 |  $MyInvocation - Auto variable containing information about the current script
 |
 Alias for Get-Content commandlet, returns content of file

Carrot, 4 bytes
2^F*

Outputs 2 normally and 4 when doubled.
Explanation normal:
2 //Input on the stack
^ //Convert to operations mode
F //Convert stack to float mode
* //Multiply stack by an empty argument (don't do anything)
  //Implicit output of stack

Explanation doubled:
2  //Input on the stack
^  //Convert to operations mode
F  //Convert stack to float mode
*2 //Multiply stack by 2
^  //Convert to string stack mode
F* //Place the literal "F*" onto the string stack
   //Implicit output of float stack

In Carrot there are three stack modes: string, float and array. Only the current stack modes stack is output at the end of the program.

TI-Basic, 4 bytes
Fairly simple. I'm wondering if there are many alternate solutions.
1:2Ans       --> prints 2
1:2Ans1:2Ans --> prints 4

Alternate solutions
1+0 <-- 3 bytes based on @alexanderbird's answer

what's wrong with (2 ?

@Oki Nothing? I just didn't consider that. Mind if I change my answer to add that one?

i don't mind. tough your solution is much fancier

Java, 121 bytes

Original Code:
class A {static int n=1;public static void main(String[]a){System.out.print(n);}}/*
class B extends A{static{n++;}}//*///

Duplicated Code:
class A {static int n=1;public static void main(String[]a){System.out.print(n);}}/*
class B extends A{static{n++;}}//*///class A {static int n=1;public static  void main(String[]a){System.out.print(n);}}/*
class B extends A{static{n++;}}//*///

Technically you have to run the main method of A the first time, and of B the second time. Still, it's one program.

You can save a byte when you remove the whitespace class A {

PHP, 48 47 43 bytes
<?php ob_end_clean();ob_start();echo++$i;?>

Try it online!
Result: 1
There's 2 PHP answers on here already, one of them looks like a port from Python and the other one breaks the error rule imo, so there's my shot at it.
Doubled:
PHP, 96 95 86 bytes
<?php ob_end_clean();ob_start();echo++$i;?><?php ob_end_clean();ob_start();echo++$i;?>

Try it online!
Result: 2
Explanation:
ob_end_clean() once called, turns off the ob_start(). However, ob_end_clean will only clean items that started within the ob_start(). So to counter act this, we clear it first, run ob_start() then execute our counter.

Welcome to PPCG! I believe you can remove some newlines (after the semicolons) to save some bytes.

Good spot, thank you :) And thanks for the welcoming!

k, 2 bytes
*2

Try it online!
A "monadic" (one argument) * means "first", and a dyadic (two argument) * is multiplication.
Therefore *2 is seen as "the first element of a list containing 2", which is 2.
*2*2 first evaluates 2*2, which is 4, and then evaluates *4, which is 4.

Carrot, 5 bytes
^F+1

Explanation:
^ --- Stack mode
F --- Convert to float
+1 --- Add 1 to the previous result
<space> -- I have no idea

Brian & Chuck, 15 bytes
>>.>?2<<<?1
!>.

Try it online!
>>.>?2<<<?1
!>.>>.>?2<<<?1
!>.

Try it twice!

This was my first attempt at learning Brian & Chuck. I took a short break after writing this answer and I've forgotten most of how it works.
It relies on the facts that:

Chuck's 4th value is zero in the single program and non-zero in the double
. is a no-op in Brian's instructions, but prints in Chuck's instructions
In the double program, Brian's instructions are appended to Chuck's, but Chuck's are ignored because they're on the 3rd line.

Ly, 6 bytes
1&+s>l

Try it online!
breakdown
Command Operation               stack content   cell
1       push 1                  1
 &+     push sum of the stack   1,1
   s    pop to backup cell      1               1
    >   next stack                              1
     l  push backup cell        1               1
            implicit output of stack
            - or second execution:
1       push 1                  1,1             1
 &+     push sum of the stack   1,1,2           1
   s    pop to backup cell      1,1             2
    >   next stack                              2
     l  push backup cell        2               2
            implicit output

Perl, 15 bytes
++$_,exit print

Try it online!
Doubled:
++$_,exit print++$_,exit print

Try it online!
Increments $_ to 1 in the first instance, print outputs $_ by default, and we pass that as an argument to exit. When doubled, print explicitly outputs ++$_ which is now 2.

TI-BASIC, 2 bytes
2!

There are also 5 more solutions, of equal or greater length.
(2

abs(2

int(2

iPart(2

round(2

These all work on the same principle. Something evaluates to 2, and twice it is merely 2*2.

You should consider changing your formatting to have your solution in a separate code block prior to your outputs for both the singlet and doublet forms

CJam, 4 bytes
1]:+

Try it online!
Explanation:
1]:+

1    push 1 to stack
 ]:+ sum stack

CJam, 1 byte
)

Try it online!
I'd say this uses 2 bytes since there is a 0 in the header. I don't know if this is a valid loophole or forbidden.

The second one isn't valid since it doesn't work without the 0

Cubix, 4 5 bytes
Of course as soon as I look at it again this presents itself.  Not as nice as the previous, but shorter.
))O@

Try it online!
  )
) O @ .
  .

Increment, output and exit.
))O@))O@

Try it online!
    ) )
    O @
) ) O @ . . . .
. . . . . . . .
    . .
    . .

Increment twice, output and exit

Julia 0.6, 41 bytes
My first two ideas were already done in python answers (check file length, use a finalizer on an object). So here I check if π is an integer to gate the code that sets π=1 and registers the print to occur on exit. Then just double π each time.
π%1>0?(π=1;atexit(()->show(π))):π*=2;

Try it online!
Try twice it online!

π>3 instead of π%1>0 works too

as well as π=2 instead of π*=2

Julia 0.6, 24 bytes
Riffing off of lungj's Python 3 answer. This works on my terminal on my mac, but not on TIO. The \r should reset back to the start of the line, so it always overwrites the previous output. Uses string interpolation with $ to execute π=2π÷1 which doubles π and uses integer division to round it to an integer. It does output "WARNING: imported binding for π overwritten in module Main" as well, but thats not an error, and is pretty close to a compiler warning.
print("\r$(π=2π÷1)");

Try it online!

Wumpus, 6 bytes
$@1$O+

Try it online!
Doubled:
$@1$O+$@1$O+

Try it online!
The first program pushes 1, adds the top two items on the stack (the 1 and an implicit 0), reflects off the end of the line, outputs and exits.
The second program does the same, except it adds two 1s to the stack, meaning it prints 2 and exits. This works for any number from 1-9.
A shorter solution may exist that takes advantage of two lines making the pointer bounce differently.

///, 20 bytes
Prints 1:
/\\1\//\/1\/2\/\//\1

Try it online!
Duplicated prints 2:
/\\1\//\/1\/2\/\//\1/\\1\//\/1\/2\/\//\1

Try it online!
How it works

The initial substitution /\\1\//\/1\/2\/\// (in both versions) searches for the string \1/ in the remainder and replaces it by /1/2//.
In the single program there is no such string, and nothing is replaced. The program is now reduced to the final \1, which prints a 1.
In the duplicated program \1/ crosses the boundary between the copies.

After substituting, the remaining program becomes /1/2//\\1\//\/1\/2\/\//\1, which is the substitution /1/2/ followed by the single program.
This substitution then replaces every 1 in the single program by 2, giving /\\2\//\/2\/2\/\//\2.
This then runs pretty much like the single program does, except for printing 2 instead of 1.

The normally redundant \ before the final 1, and the corresponding \\ in the initial substitution, are needed because without them, the substitution would be applied again to the /1/2/ result, causing an infinite loop.

Was just thinking about doing a /// submission, but it looks like you beat me to it!

Momema, 12 bytes
00 1+1*1-8*1

Try it online! This outputs 1.
Try it doubled! This outputs 02.
Explanation
The ungolfed form of the singular program 00 1+1*1-8*1 is
0   0     # set the 0th cell to 0 (this has no effect).
1   +1*1  # set the 1st cell (initialized to 0) to itself plus one (i.e. 1).
-8  *1    # output the value of the first cell as a decimal (1).

The ungolfed version of the doubled program 00 1+1*1-8*100 1+1*1-8*1 is
0   0     # set the 0th cell to 0.
1   +1*1  # increment the 1st cell.
-8  *100  # output the value of the 100th cell (0).
1   +1*1  # increment the 1st cell.
-8  *1    # output the value of the 1st cell (2).

This submission hinges on Momema's syntax: in particular, it allows leading 0s in a numeric literal to be parsed as separate numbers. This allows the leading 00 in the program to be parsed as a pointless assignment statement.
When the program is doubled, however, the 0s are no longer leading a numeric literal—they are a continuation of the literal 1 at the end of the program, forming 100.

Labyrinth, 8 5 bytes
-3 bytes thanks to @MartinEnder
Single version

^)!@

Try it online!
Double version

^)!@
^)!@

Try it online!

Nice work, this is a really neat solution! :) I got curious and set a brute force solution on this problem and it found a whole bunch of 5-byte solutions (all of which print 1 and 2, some of them with leading zeros). Feel free to add any of them to your answer https://pastebin.com/RRFxZEuN (I don't care about posting them myself, since you clearly put more effort into your 8-byte solution than I did into just brute forcing the optimal ones.)

Rust, 81 bytes
mod x{pub const Y:i8=1;}use x::*;fn main(){print!("{}",Y)}/*
const Y:i8=2;// *///

Doubled:
mod x{pub const Y:i8=1;}use x::*;fn main(){print!("{}",Y)}/*
const Y:i8=2;// *///mod x{pub const Y:i8=1;}use x::*;fn main(){print!("{}",Y)}/*
const Y:i8=2;// *///

Try it online (single)
Try it online (double)

Rust pretty much doesn't allow duplicate items in a source code. For instance, following code causes an error due to an item defined multiple times.
const Y: i32 = 2;
const Y: i32 = 2;

There are three exceptions to this rule.

Macros - which are pretty much useless, as macros don't follow the usual visibility rules - code cannot refer to a macro later in the code.
Wildcard imports - if there is a non-wildcard import, it has precedence while resolving item references. This is to help avoid incompatibilities caused by other crates (including std itself) adding more public items.
Overriding a builtin item or item from prelude - see bonus below, this way turned out to be longer, but also has more potential for improvements.

I decided to go with duplicating an item by using a glob import. This necessiated making a module.
mod x { ... }

That had a public item in it. Not public items aren't accessible outside of module that defined them. i8 type was chosen because it's the shortest integer type -- a type needs to be declared for const items, this cannot be skipped.
A string literal wasn't used as &str is 2 bytes longer, and also quotes would be necessary, not saving bytes even with removal of "{}", from main function. Adding 6 bytes is not worth it for removing 5 bytes.
pub const Y: i8 = 1;

Later I glob import this constant. Note that the constant can be overridden by a different non-wildcard declaration.
use x::*;

And a function prints whatever value Y holds. Note that Y can be overridden by a non-wildcard declaration. This is important when doubling source code.
print! ends with an exclamation mark as it is a macro. As the first parameter is a formatting pattern, I cannot use an integer directly, instead I have to specify "{}", formatting pattern.
Missing semicolon at the end of block means that this block returns a value. This is fine, as main returns () (implicit, due to not specifying another return type), and print! macro returns () (as in, it doesn't have an useful return value).
fn main() {
    print!("{}", Y)
}

Later, I want there to be a second declaration of Y, but I don't want it come into play for the first pass, so I comment it out. There is a newline, so that a line comment that will be declared later won't skip over a constant declaration. There is a space after // as there is nested comments feature, otherwise Rust would see /* inside block comment and start a nested comment.
/*
const Y:i8=2;// */

At end, I put //, so that first line of code of code is skipped when the code is doubled. It involves items that cannot be defined multiple times.
//

The execution may conntinue from second line. If it does, value of Y used by main function will be different.
 const Y: i8 = 2;

A line comment is included so that closing block comment that was needed for first pass won't cause issues.
// *///

And that's it, a program that detect it being duplicated in Rust done in 81 characters. Thank you for reading this explanation.
Bonus (alternative way for possible improvements, 93 92 bytes)
Instead of using glob imports, it's possible to override one builtin items from either a builtin type or something imported from prelude.
fn main(){println!("{}",i8::max_value())}/*
enum i8{}impl i8{fn max_value()->u8{254}}// *///

However, this solution is currently longer than the solution above.

Same length (81 bytes), but I thought I'd share a slightly different version of your answer that uses #[test] instead: TIO.

@TehPers I like the idea of using #[test], clever :).

Ruby, 10 bytes
+1;a||=p 1

Try it online!
Try it online!Try it online!
Explanation:

Single version (+1;a||=p 1):

+1 is ignored
a is assigned to 1 (printing 1 in the process) because a was previously undefined

Double version (+1;a||=p 1+1;a||=p 1)

+1 is ignored
a is set to 1+1 (2) (printing 2 in the process) because a was undefined
The next part is not executed because a is already defined

JavaScript (console), 30 bytes
[$^=1]+{valueOf:x=>alert(2-$)}

In console environments, we have the $ default global variable, which is two characters shorter than Map, which is the shortest in other environments.
The way this works:

$ is coerced to a number, and has bitwise XOR applied to it, making it 1.
The object at the end is part of an addition equation, so it is also coerced into a number, calling the valueOf function which alerts 2-$, which equals 1.

When the code is repeated, it looks like this:
[$^=1]+{valueOf:x=>alert(2-$)}[$^=1]+{valueOf:x=>alert(2-$)}

The first instance of the object now has a member operator attached, so instead of the object's valueOf being called, instead we have (object)[$^=1 /* 0 */ ], which is undefined. The first instance doesn't alert anything, but the second one does, and by now $ has been changed to 0 because $^=1 has run twice, so it alerts 2.
Or, for non-console environments, we can use Map instead of $ (34 bytes):
[Map^=1]+{valueOf:x=>alert(2-Map)}

Or, we could use...
JavaScript, 32 bytes

-0?alert(2)+'':[,a=alert(1)]=[1]

When not repeated:

-0 is false, so we go to [,a=alert(1)]=[1], destructuring with a default value. a is to be assigned to [1][1], which isn't defined, so a defaults to alert(1).

When repeated:

-0?alert(2)+'':[,a=alert(1)]=[1]-0?alert(2)+'':[,a=alert(1)]=[1]

-0 is still false, so we go to [,a=alert(1)]=[1]-0?alert(2)+'':[,a=alert(1)]=[1]
[1]-0 returns 1 which is true, so we alert(2) and coerce the undefined result to a string by adding an empty string. This returns "undefined". a is still being set to the "undefined"[1] which is this case is the letter "n". Since "n" is a value, the default alert(1) isn't run.

Wow, this is brilliant. I learnt a lot! I don't get yet why Map or $ are coerced to the value 1, though.

Perl 5, 10 bytes
print-s$0#

Try it online!
Doubled, 20 bytes
print-s$0#print-s$0#

Try it online!
Inspired by Sriotchilism O'Zaic recursive comment approach (Nice work by the way).

Octave, 25 13 11 3 bytes
3;ans=fix(ans);ans=ans*2.

Try it online! Try it doubled!
Edit 1
Got rid of the fix
1;ans=3*ans-0

Try it online! Try it doubled!
Edit 2
Got rid of the *
3;ans=ans+0

Try it online! Try it doubled!
Edit 3
Got rid of ans ...
3+0

Try it online! Try it doubled!

Google Sheets, 12
This answer is much shorter. But here's one for a "normal" = formula.
=LEN("&00001

Google Sheets auto-closes quotes and parens. This outputs 6 (the length of &000001). Here is the doubled version:
=LEN("&00001=LEN("&00001

This outputs 12 because &00001=LEN( is 11 characters, concatenated with 1 gives 12 characters.

Wow...Are you the person who's posting Google Sheets answers everywhere? They're pretty ingenious

@user Yeah, I guess I've been doing a lot of that lately, huh? I do find GS/Excel "programming" to be quite entertaining/hilarious. It's like a bit like a cult-classic movie. If someone else can get some enjoyment out of it, then I'm happy.

BRASCA, 2 bytes
Original:
C}

Doubled:
C}C}

Try it!
Try it!Try it!
Explanation
Original:
C     - Sets implicit output to number mode
 }    - Increment top of stack (stack is infinite zeroes by default)

Doubled:
C     - Sets implicit output to number mode
 }    - Increment top of stack (stack is infinite zeroes by default)
  C   - Implicit output is already set to number mode, so it does nothing
   }  - Increment top of stack again

Zsh, 9 bytes
wc -l<<<x
Note there is no trailing newline.
Attempt This Online! (outputs 1)
Attempt This Online!Attempt This Online! (outputs 2)
Explanation:

wc: output word-count information:

-l: the number of lines in the input

<<<x: and input the single-line string x

ExplanationExplanation:

wc: output word-count information:

-l: the number of lines in the input

<<<xwc: and input the single-line string xwc
-l: redundant duplication of the previous -l option
<<<x: and input a second single-line string x

Zsh, 6 bytes
If output requirements followed standard rules, we could output via exit code for 6 bytes:
grep x
Again, no trailing newline.

grep x searches for x in the (empty) input, which has no results and outputs with status code 1
grep xgrep x searches for xgrep in the (non-existent) file x, which is an error and outputs with status code 2

Attempt This Online! (returns 1)
Attempt This Online!Attempt This Online! (returns 2)
There might be an even shorter option using exit codes.

Rust, 69 bytes
use std::u8::*;fn main(){print!("{}",MIN+1)}#[test]
const MIN:u8=1;//

Try it online
Try it online (doubled)
This follows the suggestion in Konrad's bonus solution to override a standard library item and uses #[test] instead to "disable" a declaration on the next line. It's not as short as this solution, but it doesn't require reading the source.

Backhand, 3 bytes
]h

Try it online! Try it doubled!
Prints 1 as-is, and prints 2 when doubled. There is a trailing space.
There is no two-byte solution because:

The first command should produce some nonzero number, and the second should be h (print the number and halt)
but both ab and abab will execute a then b, so any such program will print the same number (not twice) when doubled.

For a three-byte program, abc runs a then b while abcabc runs aab in the order, so "a = increment = ], b = print and halt = h" works.

Lambda calculus (Nat), 5 bytes
(SBI)

Try it online!

Instructions: Copy-paste the code into the code box, select Nat, press Compile and then Run to see the Output.

Outputs in Church numeral.
SBI
\xy. SBIxy
\xy. Bx(Ix)y
\xy. Bxxy
\xy. x(xy)

Applying a Church numeral n to another m, i.e. n m, evaluates to m^n. Therefore, (SBI)(SBI) = 2 2 = 2^2 = 4.
Turns out that I already did the same thing in Flurry...

MathGolf, 1 byte
There are multiple answers possible:

): try it online or try it doubled - outputs \$1\$ and \$2\$;
⌠: try it online or try it doubled - outputs \$2\$ and \$4\$;
ó: try it online or try it doubled - outputs \$1\$ and \$2\$.

Explanation:
If the stack is empty when a numeric operator is used, it'll use an implicit \$0\$. The three programs will respectively do the following:

): Pop the top of the stack \$t\$, and push \$t+1\$
⌠: Pop the top of the stack \$t\$, and push \$t+2\$
ó: Pop the top of the stack \$t\$, and push \$2^t\$

After which the entire stack joined together is output implicitly as result.

Pip, 2 bytes
+1

Try it online!
Try the double version!

Newline 3 bytes
i\n

Note: running newline in TC mode
Output is the red text up top
Try it online

You should indicate a newline by leaving an empty line in the code block, not by using an escape sequence.

You're referring to the last line of code, correct? That is an actual newline; the string literal is 2 bytes (i and a newline), but its representation in JavaScript source is three (i\n). Your submission here should be encoded as text, not JavaScript source.

Could you provide a reference to the thread on Meta? You posted a 3-byte solution here, but the solution you link to is 2 bytes. This doesn't make sense to me.

continuing in chat

@Jakob https://chat.stackexchange.com/transcript/message/42803737#42803737

@Christopher I don't think Dennis had enough context to answer that. The size of a program is the actual size of the byte representation of the source code. Writing "1\n" in JavaScript code creates a string containing two characters, so the size of the program should be 2 bytes. You could replace that string literal with a short expression that loads the source code from a text file. That text file would need to contain a literal linefeed, not \n, and its size would be 2 bytes.

@martin can't do that without rewriting the language in a different language. Since I don't plan on using it anymore I really have no reason

@Christopher This has nothing to do with rewriting the interpreter in another language. The source code of your program in memory is 2 bytes, not 3. Whether you create that string with a literal (which takes more than 2 characters) or read it from a file (which would contain 2 characters) doesn't matter.

Ohm, 2 bytes
1Σ

Try it online!
Try the double version!
aaaaaaaaaaaaaaa i can't find a language where this is one byte aaaaaaaaaaaaaaa

What does the sigma do?

It sums an array or the stack depending on what type the TOS is

QBIC, 12 bytes
p=p+q┘Z=!p$┘

Explanation
p=p+q        Adds 1 to p (q = 1 in QBIC, and p starts out as 0)
┘            (Syntactic linebreak)
Z=!p$        Set Z$ to a string representation of p.
┘            (Syntactic linebreak)

At the end of a QBIC program, if Z$<> "" it gets printed. So when running this code once, p gets increased by 1, the result is saved in Z$, the program ends and we print 1. By running it twice, Z$ will get overridden on the second iteration by p, which is now 2.

Vim, 5 bytes
i0<esc><C-a>:

Since V is backwards compatible, you can Try it online! or Try it doubled!

Seemed doubled version outputs 1, not 2; did I missee the result?

LOGO, 16 bytes
 ct pr bf gensym

output 1.
When doubled, it becomes
 ct pr bf gensym ct pr bf gensym

output 2.
Explanation:

ClearText clears all the output.
Print just print whatever it is given.
ButFirst return the input with the first item removed.
GenSym (perhaps GenerateSymbol) return g1 the first time it is invoked, g2 the second time, etc.

Because the output of GenSym depends on previous outputs, the interpreter should be reset between runs.

JavaScript (Node.js), 60 bytes
console.log(require('fs').readFileSync(__filename).length)//

Inspired by this Python 2 answer, this reads the length of the current file and prints it, preventing any duplicates of this code from being executed with the trailing comment.
Try it online!
Try it online doubled!

BlitzMax, 13 bytes
Print..
+1..'

No trailing newline.
Newlines act as statement terminators in BlitzMax unless prevented by a ... The ' symbol introduces a line comment. So if run as-is, the program outputs the result of the expression +1, which is 1. If doubled, the second Print is commented out and the program outputs the result of +1+1, which is 2.
If you double the program a second time, you get 4, etc.

JavaScript, 41 chars

clearTimeout(1);x=setTimeout('alert(x)');

clearTimeout(1);x=setTimeout('alert(x)');clearTimeout(1);x=setTimeout('alert(x)');

Shows 3 and 4 for me using the Run code snippet button

@FliiFe, try in incognito window with all browser extensions disabled.

Ohm, 3 bytes
Original:
0Wl

Duplicated:
0Wl0Wl

Owles?
Explanation
0Wl    Main wire
0      Push 0
 W     Wrap in an array
  l    Push Length (1)
0Wl0Wl
0Wl    Push 1 ^
   0   Push another 0
    W  Wrap in an array ([0,1])
     l Push the length (2)

Try it online!
Try it online!Try it online!

><>, 9 bytes
l";3"+10p

Try it online!
Explanation
l";3"+10p
l              | Push the length of the stack to the stack; STACK[0]
 ";3"          | Push 59 and 51 to the stack;               STACK[0, 59, 51]
     +         | Add the stack top 2 items;                 STACK[0, 110]
      10p      | At codebox[0,1] put the stack top item;    STACK[0]
                   NEW CODEBOX; ln;3"+10p
ln;            | Push length, print stack top and end;

When doubled we run through the code twice, it edits the print function in the same spot but doubles the amount of items we push to the stack.
><>, 18 bytes Doubled version
l";3"+10pl";3"+10p

Try it online!

Lua, 63 bytes
a=1+(a or 0)t=setmetatable(t or{},{__gc=function()print(a)end})

This code does not have a newline at the end.
When program starts, variable a is nil, then it gets modified from nil to 1 and (if program code is doubled) from 1 to 2.
The finalizer of table t gets executed when program finishes (when memory of the table is released), it simply prints last value of variable a.
Lua 5.2+ is required.

Seems like it prints nothing. Checked it at https://www.lua.org/cgi-bin/demo. Isn't it too late to print when the finalizer is called?

@Qwertiy - Thanks for bugreport.  It is a bug on Lua demo web page.

Yep, fine: http://ideone.com/5xuJhk & http://ideone.com/poh01N

You can golf this down to 64 bytes (from 76 bytes at current) by removing whitespace (see Here)

@TaylorScott - Thanks man!  A nice round size (64) !

You should edit your post to reflect the new version and byte count (which I actually miscounted - as you can see in the version above, I forgot to include the trailing newline, so the final byte count is actually 65)

@TaylorScott - All the bytes are belong to us counted!  They are 63.  Newline was removed.

Python 3, 48 bytes
Apparently, file I/O is acceptable as an output format.
try:y*=2
except:y=1
open('x','w').write(str(y))

The 48th character is a new-line character at the end of this program.

Python 3, 62 60 bytes
This time, back to stdout and no cheating.
class X:
 def __del__(s):print(y)
try:y*=2
except:y=1;z=X()

Saved 2 bytes thanks to @OldBunny2800!

Can't you remove the newline/indent in front of class?

There shouldn't be one in front of class; do you mean the def? I think that's necessary. I don't know how to put method definition on the same line as the class definition.

I mean, would class X():def __del__(s):print(y) work?

Also, don't think you need parentheses after a class declaration.

The one liner does not work on Python 3.6.0 on macOS installed via homebrew, but it's possible works on some other Python 3.

Bash 35 bytes
trap 'echo $a' 0
a=$((2**${a:-1}))

single source output:
2

double source output:
4

This uses bash default value parameter expansion to set a to either 1 or the result of 2^a. An exit trap is defined that will print the current value of a, so each additional copy of the source will double the output.

Ruby, 31 bytes
x||=1;x*=2;END{p x;exit!};

Try it online!

You can use END instead of at_exit for -7 bytes.

@Jordan nice, thanks! I've edited to incorporate that, but your answer is still shorter so I hope that's okay with you :)

Totally fine. Nice answer!

WinDBG, 40 bytes
r$t0=d;r$t0=@$t0*2;.printf"\r%d",@$t0;$$

Outputs 26, and that doubles each time the source is appended.
How it works:
r $t0 = d;                           Initialize psuedo-register t0 to 13
r $t0 = @$t0 * 2;                    Double t0
.printf "\r%d", @$t0;                Move caret to start of output line and print t0
$$                                   Comment until the next ; (comment r $t0 = d)

Sample output:
0:000> r$t0=d;r$t0=@$t0*2;.printf"\r%d",@$t0;$$
26

0:000> r$t0=d;r$t0=@$t0*2;.printf"\r%d",@$t0;$$r$t0=d;r$t0=@$t0*2;.printf"\r%d",@$t0;$$
52

0:000> r$t0=d;r$t0=@$t0*2;.printf"\r%d",@$t0;$$r$t0=d;r$t0=@$t0*2;.printf"\r%d",@$t0;$$r$t0=d;r$t0=@$t0*2;.printf"\r%d",@$t0;$$
104

0:000> r$t0=d;r$t0=@$t0*2;.printf"\r%d",@$t0;$$r$t0=d;r$t0=@$t0*2;.printf"\r%d",@$t0;$$r$t0=d;r$t0=@$t0*2;.printf"\r%d",@$t0;$$r$t0=d;r$t0=@$t0*2;.printf"\r%d",@$t0;$$
208

Scala (interpreted), 85 Bytes
if(System getProperty "v"eq "")print(2)else{System.setProperty("v","");print("1\r")};

Commented
if(System getProperty "v"eq "") // If the system property "v" is set to ""
  print(2)                      // Print 2
else{                           // Otherwise
  System.setProperty("v","");   // Set the system property "v" to ""
  print("1\r")                  // Print 1 with a carriage return
};

Text that ends with a carriage return and not a newline will be overwritten if anything else is written to the line.
Note: likely doesn't work on all consoles, tested on Windows 8.1 command prompt. For example the TIO console.

Implicit on TIO, 2 bytes
:.

Hmm, not particularly positive how this works. I'll explain it to myself:
:.
    (implicit read integer input), duplicate stack (stack: 0, 0)
 .  increment                                      (stack: 0, 1)

Ok, now I see. : doesn't read input if the stack has a value on it.
:.:.
:     stack: 0, 0
 .    stack: 0, 1
  :   stack: 0, 1, 1
   .  stack: 0, 1, 2

Only works on TIO (:., :.:.) when the input box is empty.

Would this not also work if you redirect STDIN to an empty file, or if you press Ctrl + Shift + 2 when prompted for input?

@LyricLy Yes, but those require extra bytes.

I don't understand. Doesn't it work that way already? Both methods would be sending empty input, just like TIO does. Or am I misunderstanding the reason that it only works on TIO?

@LyricLy Yes, it works that way. But redirecting to STDIN would require, in a shell, ./interpreter sourcefile < emptyfile, and assuming you have an empty file is a standard loophole. Pressing Ctrl+Shift+2 would require user input that is not specified in the challenge, another standard loophole.

I wouldn't consider merely requiring EOF to be piped to the program a standard loophole, but I see where you're coming from.

Ruby, 21 bytes
$.+=1
END{p$.
exit!};

1x: Try it online!
2x: Try it online!

Pyt, 2 bytes
0Ł

Explanation:
0       Push 0 onto the stack [0]
 Ł      Get the length of the stack (1)

Try it online!

Doubled:
0Ł0Ł

Explanation:
0           Push 0 onto the stack [0]
 Ł          Get the length of the stack (1)
  0         Push 0 onto the stack [1,0]
   Ł        Get the length of the stack (2)

Try it online!

tinylisp, 16 bytes
((q(G(i G 2 1)))

Try it online!
Try it doubled!
How?
(q (G (function-body))) creates an unnamed lambda function that takes a variable number of arguments and names the arglist G. In our case, the body of the function is (i G 2 1), which tests if G is empty or not; if it is, we return 1; if it isn't, we return 2. In other words, if we call this function with zero arguments, it returns 1; otherwise, 2.
In the single version, therefore, we call the function without arguments: (function (with an implicit closing parenthesis). In the double version, we call the function, and then call it again with that result as an argument: (function (function (with two implicit closing parentheses).

Chip, 11+5 = 16 bytes
+5 bytes for -wc1
<b
*\ae*f
`

The active code:
*\ae*f

Activates a, e, and f which means 0x00110001.
Active code when doubled:
 b
*\ae*f
`<
*\a

Prevents activation of both a's, activates b, e, and f, which means 0x00110010.
Try it online!

SNOBOL4 (CSNOBOL4), 48 bytes
	INPUT('I',1,,'.code.tio');	OUTPUT =size(I);end;

Try it online!
Equivalent to this python answer.
Because the existence of an END label terminates the program, reading the source file is the only way to get this to work, as the program ABCABC is otherwise equivalent to ABC.
SNOBOL always reads input one line at a time so we have to use ; rather than newlines.

Microscript, 2 bytes
1

(Note the trailing space.)

Stax, 2 bytes
|X

Run online, doubled
Added for completeness. |X in Stax means increment register x and push.  Register x is implicitly initialized with 0. The top of stack is implicitly output.

SmileBASIC, 11 10 bytes
CLS?X+1X=1

Yabasic, 22 bytes
An Anonymous function that takes no input and outputs to STDOUT in graphics mode.
Clear Screen
n=n+1
?n

Note: Because this answer uses graphics mode, it does not function on TIO

Reflections, 10 bytes
_~#  _#_v

Test it!
Test it double!
Explanation:

_~: read own source and push size
#  _: convert to string
#_: print the first digit
v: reflects the IP down

Then, the program does either end when hitting the other v or when leaving the grid.

Fission, 13 bytes
O\aL;
+
$
SV;

Returns 1
Try it online!
Doubled:
O\aL;
+
$
SV;O\aL;
+
$
SV;

Returns 2
Try it online!
Fun twist with this language, that doubling source will double atoms, and each atom is in general command pointer. So my idea was to build such code that second atom will be destroyed.
  L  Created atom, moving left (mass 1, energy 0)
 a   stores in it ascii code of 'a' (97)
\    mirrors
 V   fission reactor, spliting atom into two with halved masses (48)
  ;  destroy right atom
S    conditional mirror - mirrors right, if energy is zero (default energy level)
$    increase energy by 1 (mass 48, energy 1)
+    increase mass by one (mass 49)

if one copy on source:
O    print ascii by mass of atom, destroy atom (prints 1)

if code was copied
S    conditional mirror - energy is 1 now, so goes throw
$    increase energy by 1 (mass 49, energy 2)
+    increase mass by one (mass 50)
O    print ascii by mass of atom, destroy atom (prints 2)

Second atom is created with copied code \aL; on 4th row. Mirror \ sends it to the ; on the first row, where atom is destroyed

QBasic, 12 bytes
A script that takes no input and outputs to the console. Outputs 1 when single, outputs 2 when doubled.
CLS
n=n+1
?n

Small Basic, 45 bytes
A script which takes no input and outputs to the TextWindow console.
n=n+1
TextWindow.Clear()
TextWindow.Write(n)

Try it at SmallBasic.com
n=n+1
TextWindow.Clear()
TextWindow.Write(n)
n=n+1
TextWindow.Clear()
TextWindow.Write(n)

Try it Doubled at SmallBasic.com
SmallBasic.com depends on Silverlight, and thus the links must be opened in IE to function.

Lenguage, 730750818665451459101842416358141509827966271746 bytes
Not doubled: Try it online!
Doubled: Try it online!
Not that golfed but at least it's a solution, handling loop is so hard

Python 2, 25 24 bytes
x=1
print 4*'\b',x,;x=2#

Both values of x (1 and 2) get printed when the code is repeated. However the second time, the backspace character backspaces/"erases" the 1 and prints the 2 over the top of it.
The behaviour of printing the backspace escape character \b seems quite system dependent (and it doesn't seem to work on many web REPLs...).
Trailing comment idea inspired by W W's answer.
Edit: byte saved, see comment.

Welcome to the site!

Why don't you put x=2 after the print and before the comment instead of multiplying by two before the print?

Thanks: I think that will save a byte or two...

Ahead, 7 bytes
1~@O+K~

Prints 1 on its own, 2 when doubled, 3 when tripled etc.
Try it online!

Z80Golf, 6 bytes
00000000: 3676 f630 3ce5                           6v.0<.

Try it online!
Doubled
00000000: 3676 f630 3ce5 3676 f630 3ce5            6v.0<.6v.0<.

Try it online!
Disassembly
start:
  ld (hl), $76
  or $30
  inc a
  push hl

The trick is to exclude any call or rst instructions, so that the execution exactly follows the order:

The program (one or two copies)
The nop slide, then putchar at address $8000 (exactly once), and then
halt which should be hit on return from putchar.

or $30; inc a sets up the ASCII '1' = $31 to print. push hl sets up the stack; ld (hl), $76 writes the halt instruction on the return address.
When doubled, the second inc a changes the value to ASCII '2' = $32. The other instructions are effective no-ops; the return address and the halt instruction on return don't change.

Aheui, 23 bytes
분아떠망히
아뷴

outputs 4.
Doubled:
분아떠망히
아뷴
분아떠망히
아뷴

outputs 8.
Try it on jsaheui

W, 2 bytes
1+

Explanation
1+   % Adds an (implicit) 0 (on empty input)
  1+ % Add the constant 1 by 1
     % Implicit output

MathGolf, 1 byte
Added just for completeness.
)

Try it online!

05AB1E, 2 bytes
2*

Try it online!
2 pushes 2 to the stack.
* multiplies the last 2 elements of the stack.
Doubled
05AB1E, 4 bytes
2*2*

Try it online!

Javascript (NodeJS) 44 bytes
l={get a(){console.log(z)}};z=this.z?2:1;l.a

Or in a browser environment, 38 bytes:
l={get a(){alert(z)}};z=this.z?2:1;l.a

I found this really challenging, but really interesting. I probably overlooked a much simpler way of doing this.
Using a getter was the only way I could think of so far where appending the second copy of the string would not cause the initial behaviour to run before we get a chance to intervene. When it's repeated, we get:
l={get a(){console.log(z)}};z=this.z?2:1;l.al={get a(){console.log(z)}};z=this.z?2:1;l.a

The critical part is that l.a (the getter) only ends up happening once, because the first time it becomes l.al=...

Pxem (esolang-box notation), 8 bytes.
In this docker environment Pxem program, officially given as a pair of filename and its content, is given as a file:

The first line is the file name of the pxem code.
The rest is the content of the pxem code.

Original is
.f.+.n
.

which is translated to filename .f.+.n with content ..
It outputs 46, which is ASCII code for ..
When doubled:
.f.+.n
..f.+.n
.

which is translated to filename .f.+.n with content ..f.+.n\n..
It outputs 92.
How it works
.f pushes content in reverse order
.+ does push (pop+pop) if size>=2; nop otherwise
.n does printf %d pop

Try it online!
Try it online!Try it online!

brainfuck, 41 bytes
[---.+++++++++++[.]]+++++++[->+++++++<]>.

Try it online!
Try it online!Try it online!
Contecting two brainfuck programs always output the output of first program, so 1 and 1.999... is the only choice

I remember I've seen a brainfuck solution using \b to erase but I can't find it(even not a removed one)

Python 3 (notebook), 2 bytes
+1

This only works in a notebook enviroment. Also, You can replace the 1 with any p. number and it'll work.
Try it online!

Uiua (0.0.18): 9 bytes
(unfortunately not 7 bytes because Uiua has no single-byte codepage yet)
⍣'2;'1;

Try it online or Try it online doubled
Explanation: ⍣ is the try glyph, so it attempts to pop an item off the stack and then push 2. This fails, because the stack is empty, so instead it switches to the other branch, where it pops off the (automatically pushed) error description and then pushes 1. If the code is doubled, the second time it is successful at popping an item off the stack, and so it continues on the main branch and outputs 2 instead.

05AB1E, 2 bytes
2*

Try it online!
2    # Push 2
*    # Multiply. Multiplies two by itself the first time.

Old attempt (3 bytes):
0so

Try it online!
0 can actually be any number, first item is 2^n. · can be used instead of o, Doubles last number instead of 2^n.
0    # Push 0
s    # Switch with last item
o    # 2^item

05AB1E, 2 bytes
¼¾

Try it online!
¼¾  # full program
¼   # increment counter_variable (initially 0)
 ¾  # push counter_variable
    # implicit output

Doubled, 4 bytes
¼¾¼¾

Try it online!Try it online!
¼¾¼¾  # full program
¼     # increment counter_variable (initially 0)
 ¾    # push counter_variable
  ¼   # increment counter_variable
   ¾  # push counter_variable
      # implicit output

Pxem, 0 bytes (content) + 21 bytes (filename); requires to be executed on console.

Content is empty.
Filename (escaped): \001.r.v.w.s\b2.p.d.a11.o

Try it online!
Try it online!Try it online!
How it works
When single, it just outputs 1; when doubled, it appends backspace character and 2; this is how it looks like as if it were doubled. If this would violate the rules, I'm sorry.

Thunno, \$ 2\log_{256}(96) \approx \$ 1 byte
(actually 1.65 bytes but the leaderboard doesn't accept that)
1+

Attempt This Online!
Or try it doubled
Pretty straight-forward approach. The stack starts off at [0] so the first + doesn't do anything.
Alternative approach,  \$ 3 \log_{256}(96) \approx \$ 2.47 bytes
zdL

Attempt This Online!
Or try it doubled!
(Sort-of) port of Wheat Wizard's Python solution:

zd gets the source code
L gets the length
(Implicit output of the top of the stack)

When you double it, it will run it twice, and just end up with 6 on the top of the stack.

Awk, 4 bytes
$0++

The original increments $0 to 1, which auto-prints and the doubled version ($0++$0++) just increments it twice.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Word Chain Reloaded
This is a variant of Play the word chain and Building a long chain of words .

The input is a non-empty list of unique words at least 2 chars long made of characters in [a-z]. You need to output the length of the longest possible chain, where each subsequent word starts with the last letter of the previous word. You can start with any word on the list.
Another twist is that you are allowed to repeat any single word on the list. However, you can not repeat any two-word block. For example,
cat->tac->cat is allowed, but cat->tac->cat->tac is not, because you repeated a two-word block (cat->tac). Also, you can not use the same word twice in a row (e.g. eye->eye).
Examples:

cat dog tree egg => 3 (cat->tree->egg)
new men ten whim => 5 (ten->new->whim->men->new)
truth fret heart his => 5 (fret->truth->heart->truth->his)
we were stew early yew easy => 9 (stew->were->early->yew->were->easy->yew->we->easy)
tac cat tac cot tac can => 6 (tac->cat->tac->cot->tac->can)

(Let me know if I made a mistake on any of these examples or if you come up with more.)

Python 3, 150 149 145 bytes
def f(d):
 a=[[w]for w in d]
 while a:b=a[0];a=[f+[l,y]for*f,l in a for y in{*d}-{b for a,b in zip(f,f[1:])if a==l}if l[-1]==y[0]]
 return len(b)

Try it online!
The idea for constructing successively longer paths (or in this case trails) until none longer could be created was directly inspired by grc's answer on the Play the word chain question.

"cat dog tred xy yz zx" returns 4. Is that correct? Shouldn't it be 3?

@ChasBrown xy yz zx xy is the longest chain, so 4.

Haskell, 131 141 bytes
Basically the brute force approach.. The idea is to generate all possible domino pieces, permute them, check if it's a valid combo and maximize the whole thing. The time complexity is ridiculous, the 4th test case already takes ~4s on my PC and on the TIO it doesn't seem to work!
import Data.List
p w=2+maximum[length$takeWhile(\(x,y)->x!!1==y!!0)$zip p$tail p|p<-permutations[[a,b]|(a,b)<-(,)<$>w<*>w,a/=b,last a==b!!0]]

Try it online!
Ungolfed
p w = maximum
  [ 2 + length c | p <- permutations [ [a,b] | (a,b) <- (,)<$>w<*>w
                                             , a /= b
                                             , last a == head b
                                     ]
                 , c <- [ takeWhile (\(x,y) -> x!!1 == y!!0) $ zip p (tail p) ]
  ]

Edit: Changed from Lambdabot to bare Haskell but saved a few bytes by golfing it, such that it's still less than 145 bytes :)

The last one took like 19s on my computer on TIO. btw, the reason you use Lambdabot is to avoid writing import statements, right?

Yes, I do. But I stopped doing that since nobody else was doing this, not sure about it. Why?

I'm trying to figure out who won. Typically, you include import statements in byte count. But, if you found environment that doesn't require imports, then it's ok.

Oh, I wouldn't accept an answer anyway. If you want to, then I'll change my answer because @notjagan's answer is better than mine.

I mean this is code golf, so you're in first place. Anyway, you're answer fits your name. But I'll leave it open at your request.

@geokavel moot point now O_o.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes