text:
Test a number for narcissism
A Narcissistic Number is a number which is the sum of its own digits, each raised to the power of the number of digits.
For example, take \$153\$ (3 digits):

\$1^3 + 5^3 + 3^3 = 153\$

\$1634\$:

\$1^4 + 6^4 + 3^4 + 4^4 = 1634 = 1 + 1296 + 81 + 256 = 1634\$

The Challenge:
Your code must take input from the user and output True or False depending upon whether the given number is a Narcissistic Number.
Error checking for text strings or other invalid inputs is not required. 1 or 0 for the output is acceptable. Code that simply generates a list of Narcissistic Numbers, or checks the user input against a hardcoded list, does not qualify.
OEIS A005188

Is it ok if I output True if it's such a number, but anything else (in this case the number itself) if not?

APL (15)
∆≡⍕+/(⍎¨∆)*⍴∆←⍞

Outputs 1 if true and 0 if false.
Explanation:

∆←⍞: read a line (as characters), store in ∆
(⍎¨∆)*⍴∆: evaluate each character in ∆ and raise it to the power ⍴∆
∆≡⍕+/: see if the input equals the string representation of the sum of these

what did i just read

@LagWagon God's language

GolfScript, 16 characters
~.`:s{48-s,?-}/!

Input must be given on STDIN, output is 0 or 1 indicating non-narcissistic / narcissistic number.
Explanation of the code:
~              # Evaluate the input to get a number
.              # Accumulator (initially the number itself)
`:s            # Convert number to string and assign to variable s
{              # Loop over characters of the string
  48-          # Reduce character value by 48
  s,           # Push length of input number
  ?            # Power
  -            # Subtract result from accumulator
}/
!              # Not! (i.e. iff accumulator was zero it was a narcissistic number)

I did a double-take on ~.` but it seems impossible to improve. Nice one.

Mathematica, 43 chars
Tr[#^Length@#&@IntegerDigits@#]==#&@Input[]

Perl, 38 characters
perl -lpe '$@=y///c;$s+=$_**$@for/./g;$_=$_==$s'

A pretty straightforward implementation.
Here's a slightly different version that fits in 35 characters:
perl -lpe '$@=y///c;$s+=$_**$@for/./g;$_-=$s'

This version outputs a false value if the input is narcissistic, otherwise it outputs a (Perl-accepted) true value. One might argue that this backwards version falls within the limits of the challenge description, but upon reflection I decided not to. I'm not that desperate to improve my score. Yet.

“Error checking for text strings or other invalid inputs is not required.” – So why not suppose the input will be valid number, without trailing newline? echo -n 153 | perl -pe '…' will work without -l.

I think so long as you define what your true and false outputs are, it should be legal

Strictly speaking, the wording of the challenge text does leave a bit of ambiguity as to what True/False or 0/1 should mean, so I'll let this one pass. A different script of equal length that returns true for narcissistic values would have the advantage, though.

Same idea but shorter: perl -pe'map$s+=$_**@y,@y=/./g;$_=$_==$s'

J, 23 chars
(".=+/@("."0^#))(1!:1)1

(1!:1)1 is keyboard input (returning a string).
". converts input to a number; "0 specifies a rank (dimension) of 0, in other words, taking each character and converting it to a number.
^ is the power function and # is the length function, thus taking each digit to the power of the length of the string (equivalently, the number of digits).
+/ is just sum, and = is comparing the sum and number.

"Your code must take input from the user and output True or False depending upon whether the given number is a Narcissistic Number." (emphasis mine)

@JanDvorak My bad -- added keyboard input.

Ruby, 34+5=39
With command-line flags
ruby -nlaF|

Run
p eval [$F,0]*"**#{~/$/}+"+"==#$_"

Outputs true or false.

This may be the most Ruby flags I've ever seen in a legitimate code golf :P

R, 71 69 66 56 48
Reduced by 8 bytes thanks to @Giuseppe! The idea was to perform the integer division before the modulo operation.
i=nchar(a<-scan()):0;a==sum((a%/%10^i%%10)^i[1])

(3-year) old version with corresponding explanation:
i=nchar(a<-scan()):1;a==sum(((a%%10^i)%/%10^(i-1))^i[1])

a<-scan() takes a number (integer, real,...) as input (say 153 for the example).
i becomes a vector containing 3 to 1 (the number of characters of a being 3).
%% is vectorized so a%%10^i means a modulo 1000, 100 and 10: it therefore gives 153, 53, 3.
(a%%10^i)%/%10^(i-1) is the integer division of that vector by 100, 10, 1: therefore, 1, 5, 3.
We elevate that with the first element of i which is the number of characters (here digits) of a, i. e. 3, thus giving a vector containing 1, 125, 27 that we sum and compares to a.

Does the integer division always round down? Otherwise, you could run into problems with e.g. 370 (a narcissistic number) turning into 4,7,0 (which would return false) or 270 (non-narcissistic) turning into 3,7,0 (returning true).

Integer division doesn't round... The integer division of 370 by 100 is 3 with the remainder of 70 and not 3.70.

48 bytes...somebody bumped this to the homepage!

Python 3, 56 bytes
Not very obfuscated, but a simple solution.
s = input()
print(int(s)==sum(int(c)**len(s)for c in s))

The [ and ] are unnecessary, and you can drop the space in front of for too, so: sum(int(c)**len(s)for c in s)

That's awesome! Thanks for the tip.

You can save two characters by removing the spaces in s = input() and another one by moving this to 2.7 where print isn't a function.

Good point, edited.

I think you should point out that adding braces to print (hence one character more) would make this a valid Python 2.x and Python 3.x solution.

In Python 2.7 first row must by s=raw_input()

You're absolutely right. Rather than add the four characters, I'll just switch it back to Python3 where it was 57 chars.

Was workin on the same approach:(

Fixed your byte count. Also, you can remove those 2 spaces on the first line.

Wouldn't lambda s:int(s)==sum(int(c)**len(s)for c in s) work?

You can actually get 43 bytes using Python 2

PHP, 80 74 66 chars
Very straightforward PHP solution:
<?for(;$i<$l=strlen($a=$argv[1]);)$s+=pow($a[$i++],$l);echo$s==$a;

It assumes error_reporting doesn't include notices, otherwise quite a few extra characters will be needed to initialize $s=0; and $i=0.
Thx @manatwork for shortening many chars.

Don't assign $a and $l in separate statements. <?for($i=0;$i<$l=strlen($a=$argv[1]);$i++){$s+=pow($a[$i],$l);}echo$s==$a; is shorter.

As you already have a statement which generate a notice, just add another: remove the loop control variable initialization. Incrementing the loop control variable also not need to be a standalone statement. And the braces are definitely not needed: <?for(;$i<$l=strlen($a=$argv[1]);)$s+=pow($a[$i++],$l);echo$s==$a;.

@manatwork: Thank you for the warm welcome to codegolf :)

Can be golfed to this for(;$i<$l=strlen($a=$argn);)$s+=$a[$i++]**$l;echo$s==$a;

K, 24 23
{x=+/xexp["I"$'a]@#a:$x}

Shaved 1 char with reordering
{x=+/{x xexp#x}"I"$'$x}

Dc: 48 characters
[1pq]Sr?d0rdZSz[d10/r10%lz^rSh+Lhd0!=c]dScx+=r0p

Sample run:
bash-4.1$ dc -e '[1pq]Sr?d0rdZSz[d10/r10%lz^rSh+Lhd0!=c]dScx+=r0p' <<< '153'
1

bash-4.1$ dc -e '[1pq]Sr?d0rdZSz[d10/r10%lz^rSh+Lhd0!=c]dScx+=r0p' <<< '1634'
1

bash-4.1$ dc -e '[1pq]Sr?d0rdZSz[d10/r10%lz^rSh+Lhd0!=c]dScx+=r0p' <<< '2013'
0

Never actually used dc, save for frantic typos in attempt to write cd

R, 53 bytes
sum(scan(t=gsub("(.)","\\1 ",x<-scan()))^nchar(x))==x

The gsub regex inserts spaces in between characters, so that the scan function will be able to read the number into a vector of digits.

+1 i would have never thought of doing that, it's brilliant.

Kona, 18
...
{x=+/(0$'u)^#u:$x}

Powershell, 75 63 62 60 58
Edit: Updated per @Iszi's comment (note: this counts on $x not existing)
Edit: Added @Danko's changes.
[char[]]($x=$n=read-host)|%{$x-="$_*"*$n.length+1|iex};!$x

58 56 chars
If input is limited to 10 digits (includes all int32)
($x=$n=read-host)[0..9]|%{$x-="$_*"*$n.length+1|iex};!$x

I was wondering if someone was going to do PowerShell before I did.

Save 12 characters by adding another variable $x and using += to do your summing instead of measure -sum then test $x-eq$n.

@Iszi - Thanks for pointing that out. I updated the answer.

For future reference, if measure -sum is ever actually necessary, you could get away with just measure -s.

More tips for PowerShell you might want to check out. http://codegolf.stackexchange.com/q/191/9387 I'm going to have to go edit some of my other answers, now.

62 chars solution that doesn't count on $x not existing: $x=$n=read-host;$n-split''|%{$x-=[math]::pow($_,$n.length)};!$x   You set $x=$n initially, subtract from $xin the loop, and then compare it to0` at the end.

61 chars: ($x=$n=read-host)-split''|%{$x-=[math]::pow($_,$n.length)};!$x

@DankoDurbić, Nice! Type coercion often comes in handy with PoSh code golfing. I only get 62 though when I run '($x=$n=read-host)-split""|%{$x-=[math]::pow($_,$n.length)};!$x'.length

@Rynant Good point. I ran your length check in PowerShell and came up with 62 as well. When running a length check similarly against the actual script, it comes up 61. This is probably because of how PowerShell handles the '' which you replaced with ''. I took the original script into Excel to double-check with =LEN("($x=$n=read-host)-split''|%{$x-=[math]::pow($_,$n.length)};!$x") and got 62 also. Of course, we could always count it manually - but who really does that?

Correction: "...how PowerShell handles the '' which you replaced (appropriately, for the purposes of counting characters) with ""."

You can shorten [math]::pow with mutiplication. For example, [math]::pow(2,3) is "1*2*2*2"|iex, or generally [math]::pow($a,$b) is "1"+"*$a"*$b|iex, which is two characters shorter. With this little trick, I get [char[]]($x=$n=read-host)|%{$x-="1"+"*$_"*$n.length|iex};!$x  which should be 60 characters, if I'm counting right. This doesn't quite work with -split'' because split returns empty strings at the beginning and the end (why?) "123"-split'' is actually "","1","2","3","".

@DankoDurbić I don't know why -split'' does that, but that's why my Keith Number Checker pipes it to ?{$_}. I used to use ?{$_-ne''} but Rynant pointed out that (for some reason I don't understand either) -ne'' is not needed. I like that, by sending [char[]] objects through iex, you're completely side-stepping the issue of object type - in fact, you're leveraging it to your advantage to build out the exponent equations! I'll have to remember that!

@DankoDurbić Thanks, updated again. @Iszi - ?{$_} works because the result of the ScriptBlock for the Where-Object CmdLet is coerced to a bool, and empty strings evaluate as False (see [bool]''). You have to be careful when filtering integers because 0 evaluates to False (try 0,1,2|?{$_} vs '0','1','2'|?{$_})

@Rynant Great information. So, I just have to keep in mind only to use filtering like that when working on numbers as strings, not integers, and I'm good?

Just realized that you can replace the {$x-="1"+"*$_"*$n.length|iex} part with {$x-="$_*"*$n.length+1|iex} which saves another two characters.

Since PowerShell's default number type is int32, are your solutions really any different in limitations?

Python 2.x - 51
Same concept as crazedgremlin's solution for Python 3.x:
s=input();print s==sum(int(c)**len(`s`)for c in`s`)

C - 97 93 characters
a,b;main(c){scanf("%d",&c);b=c;for(;c;c/=10)a+=pow(c%10,(int)log10(b)+1);printf("%d",a==b);}

With indentation:
a,b;
main(c) {
  scanf("%d",&c);
  b=c;
  for(;c;c/=10)
    a+=pow(c%10,(int)log10(b)+1);
  printf("%d",a==b);
}

You don't have to define int for global variables.

Woah. You're reading the input into argc.

Also, shouldn't having to do -lm at compile-time count +1 byte?

@Blacksilver the -lm flag is not required for C89 compilers.

Aha. Learn a new thing every day.

05AB1E (legacy), 7 bytes
DSDgmOQ

Try it online!
-2 bytes thanks to @daHugLenny

You can replace §1ô with S

Haskell 2010 - 76 characters
main=do x<-getLine;print$(==x)$show$sum$map((^length x).(+(-48)).fromEnum)x

You shouldn't post the number of ms to run the code, but the number of chars you used. ;)

Bash, 64 chars
for((a=$1;a>0;s+=(a%10)**${#1},a/=10));do :; done;echo $[s==$1]

    a=$1;p=${#a};for((;a>0;a/=10));do s=$((s+(a%10)**p));done;echo $((s==$1))

You are using variable p in a single place, so no need for it. You can move the initialization of variable a into the for to spare its separate ;: for((a=$1;a>0;a/=10));do s=$[s+(a%10)**${#1}];done;echo $[s==$1].

By moving the evaluation into the for one more character can be shortened: for((a=$1;a>0;s+=(a%10)**${#1},a/=10));do :; done;echo $[s==$1].

Oh, curious! I tried something like that, but it didn't work. Curious what went wrong.

Awk: 40 39 characters
{for(;i<NF;)s+=$(i+++1)**NF;$0=$0==s}1

Sample run:
bash-4.1$ awk -F '' '{for(;i<NF;)s+=$(i+++1)**NF;$0=$0==s}1' <<< '153'
1

bash-4.1$ awk -F '' '{for(;i<NF;)s+=$(i+++1)**NF;$0=$0==s}1' <<< '1634'
1

bash-4.1$ awk -F '' '{for(;i<NF;)s+=$(i+++1)**NF;$0=$0==s}1' <<< '2013'
0

JavaScript - 70 58 characters
for(i in a=b=prompt())b-=Math.pow(a[i],a.length)
alert(!b)

Note:
If you're testing this in your dev console on Stack Exchange, be aware that there are a number of non-standard properties added to String.prototype that will break this solution, such as String.prototype.formatUnicorn. Please be sure to test in a clean environment, such as on about:blank.

I count 70 characters there.

@manatwork, whoops, forgot to count the newline.

Great trick that decrementation!

it always returns true for me, regardless of input

@koko, I've added a note to explain why you're receiving incorrect results.

You can save some bytes by using the ** operator instead of Math.pow

Lua (101 chars)
Lua isn't known for being concise, but it was fun to try anyway.
for n in io.lines()do l,s=n:len(),0 for i=1,l do d=n:byte(i)s=s+(d-48)^l end print(s==tonumber(n))end

Improvements welcome.

As it is not required that your program can handle and process a list of numbers, I would not use bytes to implement that functionality. Replacing the loop for n in io.lines()do [...]end with n=io.read() saves some bytes (TIO).

Delphi - 166
uses System.SysUtils,math;var i,r,l:integer;s:string;begin r:=0;readln(s);l:=length(s);for I:=1to l do r:=round(r+power(strtoint(s[i]),l));writeln(inttostr(r)=s);end.

With indent
uses System.SysUtils,math;
var
  i,r,l:integer;
  s:string;
begin
  r:=0;
  readln(s);
  l:=length(s);
  for I:=1to l do
    r:=round(r+power(strtoint(s[i]),l));
  writeln(inttostr(r)=s);
end.

Java - 84 bytes
(a,l)->{int s=0;for(byte c:a.getBytes())s+=Math.pow(c-48,l);return a.equals(""+s);};

Non-lambda version: 101 bytes:
boolean n(String a,int l){int s=0;for(byte c:a.getBytes())s+=Math.pow(c-48,l);return a.equals(""+s);}

Called like this:
interface X {
    boolean n(String a, int l);
}

static X x = (a,l)->{int s=0;for(byte c:a.getBytes())s+=Math.pow(c-48,l);return a.equals(""+s);};

public static void main(String[] args) {
    System.out.println(n("153",3));
    System.out.println(n("1634",4));
    System.out.println(n("123",3));
    System.out.println(n("654",3));
}

Returns:
true
true
false
false

You can remove the parenthesis around the lambda arguments, a,l-> works exactly the same.

I know you've answer this almost a year ago, but you can golf two bytes: (a,l)-> can be a->l-> and byte can be int: a->l->{int s=0;for(int c:a.getBytes())s+=Math.pow(c-48,l);return a.equals(""+s);}

Japt, 14 9 7 bytes
¶ì_xpZÊ

Try it online

Explanation
Implicit input of integer U.
ì_

Convert U to an array of digits (ì), pass it through a function and convert back to an integer after.
xpZÊ

Reduce by addition (x), raising each element to the power (p) of the length (Ê) of the array in the process.
¶

Check if the result is strictly equal to U.

I think ¥U¬®n pUlÃx would work for 11 bytes ;)

Vyxal, 8 6 bytes
f⁰Le∑=

Try it Online!
f      # Map each digit to integer
   e   # (for each) to the power of
 ⁰L    # Input length
    ∑  # Is sum...
     = # Equal to
       # (Implicit input)?

-2 thx to lyxal.

Try it Online! for 5 bytes

F# - 92 chars
let n=stdin.ReadLine()
n|>Seq.map(fun x->pown(int x-48)n.Length)|>Seq.sum=int n|>printf"%b"

Common Lisp - 116 102 characters
(defun f(m)(labels((l(n)(if(> n 0)(+(expt(mod n 10)(ceiling(log m 10)))(l(floor n 10)))0)))(= m(l m))))

Formatted:
(defun f(m)
  (labels((l(n)
            (if(> n 0)
               (+(expt(mod n 10)(ceiling(log m 10)))
                 (l(floor n 10)))
               0)))
    (=(l m)m)))

Smalltalk - 102 99 characters
[:n|a:=n asString collect:[:e|e digitValue]as:Array.^n=(a collect:[:each|each raisedTo:a size])sum]

At the Workspace, send value: with the number, and Print It.

C#, 117
using System.Linq;class A{int Main(string[] a){return a[0].Select(c=>c-'0'^a[0].Length).Sum()==int.Parse(a[0])?1:0;}}

Retina, 118 bytes
Byte count assumes ISO 8859-1 encoding.
.*
$0 $0¶$0
(?<=^\d*)\d
x
(?=.*$)
¶
0¶

\d+
$*
¶(1+)
¶$1 $1
{`^x ?

}s`(?<=x.*)1(?=1* (1+))
$1
 1*

1¶1
11
^(1*)¶+\1\b

Try it online

Explanation
.*                          # Copy number 3 times. For Length, Unary, and Digits
$0 $0¶$0
(?<=^\d*)\d                 # Convert first copy to x's (Length)
x
(?=.*$)                     # Split up digits of last copy, each on their own line
¶
0¶                          # Remove zeros, because they leave blank lines

\d+                         # Convert to unary
$*
¶(1+)                       # Duplicate each separated digit
¶$1 $1
{`^x ?                      # While x's exist, remove an x ...

}s`(?<=x.*)1(?=1* (1+))     #     and multiply each value by the digit (nth power)
$1
 1*                         # Remove original digits

1¶1                         # Remove lines between digits
11
^(1*)¶+\1\b                 # Match if values are equal

Haskell, 68 66 bytes
d 0=[]
d n=mod n 10:d(div n 10)
sum.(\a->map(^length a)a).d>>=(==)

Usage:
*Main> sum.(\a->map(^length a)a).d>>=(==) $ 1634
True

Jelly, 6 bytes
D*L$S=

Try it online!
D        Get the digits of the input
 *L$     Raise each element to power of its length
    S    Sum
     =   Equals input?

APL (Dyalog Unicode), 8 bytesSBCS
Tacit prefix function taking the input as a string.
⍎≡1⊥⍎¨*≢

Try it online!
⍎ is the evaluated argument
≡ identical to
1⊥ the sum (lit. convert from base-1) of
⍎¨ the evaluated characters (i.e the digits)
* raised to the power of
≢ the tally of characters (i.e. digits)

Julia 1.0, 32 bytes
!n=sum(digits(n).^ndigits(n))==n

Try it online!

Uiua, 12 bytes
=/+ⁿ⧻.-@0°⋕.

Try it
Explanation:
-@0°⋕.

Convert the number to a list of digits.
ⁿ⧻.

Raise each to the power of the list's length.
=/+

Is this list's sum equal to the original?

Not the sortest but my take.
Python 2.7: 59 60 chars
a=input();(0,1)[sum(int(i)**len(str(a))for i in str(a))==a]

It's supposed to output true or false (also needs to take input).

@Timtech or 1 and 0

@EduardFlorinescu Still needs to take input.

@lszi now should work ;)

Yes, it seems to work now.

For converting boolean value to integer int(BoolExpr) is shorter than (0,1)[BoolExpr]. +(BoolExpr) even shorter.

Pyth, 13 characters
JwqvJsm^vdlJJ

Explanation:
Jw                J=input()
       ^vdlJ      eval(d)^len(J)
      m^vdlJJ     map each character in J to eval(d)^len(J)
  qvJsm^vdlJJ     print(eval(J)==sum(map each character in J to eval(d)^len(J)))

Python, 90 Bytes
a,z=input(),[]
for x in list(a):z.append(int(x)**len(a))
print(1 if sum(z)==int(a) else 0)

JavaScript, 56 characters
n=prompt();n.split('').reduce((a,i)=>a+i**n.length,0)==n
This makes use of the exponentiation operator, so you have to be running a modern browser for this to work.

Perl, 27 +3 = 30 bytes
Run with -F.  Older versions of Perl might require you to run with -nF instead, if -F does not imply -n.
grep$;+=$_**$#F,@F;say$_==$

Prints 1 if narcissistic, prints nothing otherwise.
(thanks to @Dada for byte-count correction, and for -2 bytes)

grep$;+=$_**$#F,@F;say$_==$ to save two bytes ($; instead of $a, and grep...,@F instead of grep{...}@F). However, note that -F counts as 3 bytes (-, F and a space).

C, 252 220 225 111 bytes
int f(char *a){for(int i=0;i<strlen(a);i++){r+=((int)a[i]);for(int j=0;j<strlen(a);j++)r*=r;}return r==(int)a;}

Returns 0 if false and 1 if true. Thanks to @DrMcMoylex for saving many bytes and explaining stuff.

Welcome to the site! Some tips for you: 1) You have a lot of unnecessary whitespace. You could remove most of the newlines and spaces/indentation and it would still run fine. 2) A function is allowed, so you could return '1' or '0' instead of printing it. That would save a lot of bytes. 3) Since you're only doing one thing in each 'for' loop, you could join the inner code with the loop itself. For example: for(int i=0;i<strlen(a);r+=a[i++])

@DrMcMoylex How would you know the output if I used return? There's nothing printed in the terminal...

You could write a small wrapper to print the return value of the function

@DrMcMoylex Using printf instead of making a new function uses less bytes, I believe. Thanks for the welcome, btw!

No that's not what I meant. I meant you don't need to print anything. Returning is a valid form of output. You could print the return value for testing, but your submission can just be a function. Then you won't need to parse input or print the output. For example int f(char *a){for(int i=0;i<strlen(a);i++){r+=((int)a[i]);for(int j=0;j<strlen(a);j++)r*=r;}return r==(int)a;}

Clojure, 85 bytes
#(= n(int(reduce +(vec(map#(Math/pow(Character/digit % 10)(count(str n)))(str n))))))

Usage is like so:
(#(...) {number})

Ungolfed (with commentary):
(defn narcissistic [n]
  ; The function is altered a bit, to improve readability.
  ; The double arrow means that a result of a function will get "chained"
  ; onto the next function as the last argument:
  ; (->> 1 (* 2) (+ 3)) -> (->> (* 2 1) (+ 3)) -> (+ 3 (* 2 1))
  (->> n
    ; Converts it to a string, for the next function
    ; 153 -> "153"
    str
    ; Converts the string to an array of characters,
    ; which is then raised to the powers equal to the length of the number:
    ; 153 -> (1.0 125.0 27.0)
    (map (#(Math/pow (Character/digit % 10) (count (str n)))))
    ; Converts the array to a vector (reducing only works with vectors)
    ; (1.0 125.0 27.0) -> [1.0 125.0 27.0]
    vec
    ; Reduces the vector by adding them
    ; [1.0 125.0 27.0] -> 153.0
    (reduce +)
    ; Turns that into an integer
    ; 153.0 -> 153
    int
    ; Checks if that's equal to the original n
    ; 153 = 153 -> true
    (= n)))

Befunge 98, 58 bytes
1-00p&:a\v
 00g1+00p>:a%\a/:!kv
 \:9`kv00gk:00gk*+>
@.!-$<

Try it Online!
I'm sure this can be golfed further. I will take another look at it and add an explanation later...

Add++, 16 bytes
L,BDdbLdXBcB`sA=

Try it online!

K (ngn/k), 22 bytes
{x~+/*/'(#:r)#'r:10\x}

Try it online!

there's no need for a : after a monadic verb, #:r -> #r

Can get it down to 18 bytes with {x~+/*/&[10\x]'$x}

Ly, 51 bytes
ns>lS0sp11[ppl:Isp>l<ysp>l<sp>,^<l`sy,=!]>&+s<<l=fp

Try it online!

Brachylog, 10 bytes
lg;?↔z^ᵐ+?

Try it online!
The predicate succeeds if the input is an Armstrong number and fails if it is not. If run as a full program, success prints true. and failure prints false.
lg;?↔z     A list of pairs [a digit of input, the length of input].
      ^ᵐ   A list of numbers where each is a digit of the input raised to the power of its length.
        +  The sum of those numbers.
         ? Attempt to unify that sum with the input.

Originally, this was nine bytes, but I realized that if I gave it a number more than nine digits long it would stop acting correctly, as previously I hadn't put g in there and it worked by virtue of single-digit lengths being length-1 sequences of themselves.

Vyxal 3, 5 bytes
Lᵛ*∑=

Try it Online!
cool

Swift 5.9, 82 bytes
let f={n in"\(n+0)".reduce(0){i,y in"\(n)".reduce(1){x,_ in Int("\(y)")!*x}+i}==n}

Python 2.7 - 57 chars
i=`input()`
print`sum(map(lambda x:int(x)**len(i),i))`==i

There is a shorter Python answer, but I might as well toss in my contribution.
i=`input()`

i is set to input() surrounded by backticks (which is surprisingly hard to type through SE's markdown interpreter). Surrounding x with backticks is equivalent to str(x). [backtick]input()[backtick] saves two characters over raw_input() in any case where we can assume the input is an int, which we're allowed to do:

Error checking for text strings or other invalid inputs is not required.

Once i is a string containing the user's input, the next line is run. I'll explain this one from the inside out:
map(lambda x:int(x)**len(i),i)

map is a function in Python that takes a function and an iterable as arguments and returns a list of each item in the iterable after having the function applied to it. Here I'm defining an anonymous function lambda x which converts x to a string and raises it to the power of the length of i. This map will return a list of each character in the string i raised to the correct power, and even nicely converts it to an int for us.
`sum(map(lambda x:int(x)**len(i),i))`

Here I take the sum of each value in the list returned from the map. If this sum is equal to the original input, we have a narcissistic number. To check this, we either have to convert this sum to a string or the input to an int. int() is two more characters than two backticks, so we convert this to a string the same way we did with the input.
print`sum(map(lambda x:int(x)**len(i),i))`==i

Compare it to i and print the result, and we're done.

Racket 115 bytes
(let*((l(number->string n))(g(string-length l))(m(for/sum((i l))(expt(string->number(string i))g))))(if(= m n)1 0))

Ungolfed:
(define (f n)
  (let* ((l (number->string n))
         (g (string-length l))
         (m (for/sum ((i l))
              (expt (string->number(string i)) g))))
    (if (= m n) 1 0)))

Testing:
(f 153)
(f 1634)
(f 123)
(f 654)

Output:
1
1
0
0

C#, 103 Bytes
Golfed:
bool N(int n){double a=0;foreach(var d in n+""){a+=Math.Pow(int.Parse(d+""),n+"".Length);}return a==n;}

Ungolfed:
public bool N(int n)
{
  double a = 0;

  foreach (var digit in n.ToString())
  {
    a += Math.Pow(int.Parse(digit + ""), n.ToString().Length);
  }

  return a == n;
}

Testing:
Console.WriteLine(new NarcissisticNumber().N(153));
True

Console.WriteLine(new NarcissisticNumber().N(1634));
True

Factor, 90 bytes
[ read [ length ] [ >array [ 1string ] map [ 10 base> ] map ] bi [ swap ^ ] with map sum ]

More readable and explained:
[
    read                                  ! input
    [ length ]                            ! a function which gets the length
    [ >array [ 1string ] map [ 10 base> ] map ] ! another which turns a number into an array
    bi                                    ! apply both to the string input
    [ swap ^ ] with map sum               ! raise each digit to the length power and sum
]

Clojure, 110 bytes
(fn[](let[s(read-line)p #(Integer/parseInt(str %))](=(p s)(reduce + 0(map #(int(Math/pow(p %)(count s)))s)))))

Reads in the user input, maps over the digits, raising each to a power equal to the number of digits in the number, then checks that the sum of the digits equals the number itself.
Ungolfed (and neatened up):
(defn narcissistic? []
  (let [n-str (read-line)
        parse #(Integer/parseInt (str %))
        pow #(int (Math/pow % (count n-str)))
        powd-digits (map #(pow (parse %)) n-str)]
    (= (parse n-str) (reduce + 0 powd-digits))))

JavaScript ES6, 50 bytes
v=>[...s=v+""].map(x=>v-=Math.pow(x,s.length))&&!v

Convert the number to a string and iterate through the digits,
subtract the power computation from the original number
use the ! operator to invert the logic so that a 0 result returns true and non-zero returns false.

k, 24 bytes
{x=+/*/(#$x)#,"I"$'$x}

R, 173 Bytes
a=readline()
b=as.numeric(strsplit(as.character(a),"")[[1]])
x=(b)^length(b)
if(sum(x)==as.numeric(paste(b,sep="",collapse=""))){
   print("true")
} else{
  print("false")
}

Jelly, 7 bytes (non-competing)
D*DL$S⁼

Try it online!
Or alternatively (uses 2 chains):
Dµ*LS⁼Ḍ

Explanation of the first code:
 D* DL$S⁼  Main link (monadic). Arguments: z
⁸          (implicit) z
 D         List of digits of z
   ⁸       (implicit) z
    D      List of digits of z
     L     Length of z
      $    Last two links as a monad
  *        Exponentiation with base x and exponent y
       S   Sum of z
         ⁸ (implicit) z
        ⁼  Check if x equals y

Pyke, 8 bytes (noncompeting)
YQ`lL^sq

Try it here!
 Q`l     -   len(str(input))
    L^   -  map(^ ** V)
Y        -   digits(input)
      s  -  sum(^)
       q - ^ == input

JavaScript (ES6), 56 bytes
eval(`${n=prompt()}0`.split``.join(`**${n.length}+`))==n

Pushy, 9 bytes
Note that this answer is non-competing as Pushy postdates the challenge. However, I thought I'd post it because it's interestingly short for a simple stack-based language:
VsLKeS^=#

Try it online!
It works like this (how the two stacks would look for the example input is shown on the right):
    \ Implicit input, for example 1634.  [1634], []
V   \ Copy into second stack.            [1634], [1634]
s   \ Split into individual digits       [1,6,3,4], [1634]
L   \ Push stack length                  [1,6,3,4,4], [1634]
Ke  \ Raise all to this power            [1,1296,81,256], [1634]
S   \ Take sum                           [..., 1634], [1634]
^=  \ Check equality with initial input  [..., True], []
#   \ Output this boolean (as 0/1)

Perl 6, 30 bytes
{$_==sum .comb.map(* **.comb)}

Pretty straightforward.  The chars method would be more typically used to get the number of characters in the input string, but comb returns those characters as a list, which evaluates to the number of characters in numeric context, and saves us a byte.

25 bytes

JavaScript (ES7), 43 38 bytes
Takes input as a string.
n=>n==eval([...n,0].join`**n.length+`)

Try It

f=
n=>n==eval([...n,0].join`**n.length+`)
o.innerText=f(i.value="153")
oninput=_=>o.innerText=f(i.value)
<input id=i type=number><pre id=o>

Bash, 54 bytes
echo $[ `printf "+%c**${#1}" $(fold -w1<<<$1)` == $1 ]

Try it online!
Takes input as parameter, outputs 1 if is narcissist, 0 if not.
fold prints each digit one per line, printf adds +<digit>**<length> forming the arithmetic expression which is evaluated and compared to the original input.

Python 2, 44 bytes
I think this is the shortest you can get for Python. Uses a lambda rather than a full program.
lambda s:sum(int(x)**len(`s`)for x in`s`)==s

Try it online!
Based off @danmcardle's answer.
Original answer, 51 bytes
lambda s:sum(map(lambda x:int(x)**len(`s`),`s`))==s

Try it online!

You could use strings as input and save a byte.

Pyth, 10 bytes
qsm^sdl`Q`

Verify the test cases.

Perl 5, 24 bytes
21 bytes of code + 3 for -pF flags
for$i(@F){$_-=$i**@F}

Try it online!

Swift 3.2: 107 characters
Of course Swift is absolutely not a quick language but I thought I would try:
func n(s:String){let c=s.utf8.map{Double($0)-48};print(c.reduce(0){$0+pow($1,Double(c.count))}==Double(s))}

JavaScript 46 bytes

F=n=>![...n].reduce((x,c)=>x-(+c)**n.length,n)

console.log(F("153") == true)
console.log(F("370") == true)
console.log(F("371") == true)
console.log(F("152") == false)
console.log(F("150") == false)

Is it necessary to convert c into number?

Pyt, 11 bytes
ĐĐḶ⌊⁺⇹ą⇹^Ʃ=

Explanation:
                      Implicit input
ĐĐ                    Duplicate the input twice
   Ḷ⌊⁺                Get number of digits in the input
      ⇹ą              Convert input to array of digits
        ⇹^Ʃ           sum the digits raised to the power of the number of digits
           =          equals input?

Try it online!

JavaScript 7, 41 Bytes
s=>[...s].map(x=>N+=x**s.length,N=0)|N==s

CJam, 12 bytes
{_Ab_,f#:+=}

Try it online!
Explanation:
{          }   anonymous block, input: 1634
   b           get digits in base
  A              10: [1 6 3 4]
     ,         take the length: 4
       #       and raise
      f          each element
    _              of the list of digits
               to that power: [1 1296 81 256]
        :      fold over
         +       addition: 1634
          =    and compare
 _               to the original: 1 (true)

Kotlin, 60 bytes
map{Math.pow(it-'0'+0.0,length+0.0)}.sum()==this.toInt()+0.0

Beautified
map {
    Math.pow(it - '0' + 0.0, length + 0.0)
}.sum() == this.toInt() + 0.0

Test
fun String.f() =
map{Math.pow(it-'0'+0.0,length+0.0)}.sum()==this.toInt()+0.0

fun main(args: Array<String>) {
    (0..1000).filter { it.toString().f() }.forEach { println(it) }
}

TIO
TryItOnline

Javascript (ES6) 46 bytes - Not competing
n=>(s=[...''+n]).forEach(v=>n-=v**s.length)|!n

Explanation:
n=>
(s=[...''+n])        // Convert input to array of chars and assign to s
  .forEach(v=>       // Loop over s (returns undefined)
    n-=v**s.length)  // reduce input by char^length
  |                  // undefined is falsy, so we OR
  !n                 // OR with negated input
                     // returns 1 if 0, 0 otherwise

Pari/GP, 30 bytes
n->[n-=d^#s|d<-s=digits(n)];!n

Try it online!

Tcl, 77 bytes
proc N n {expr [join [lmap d [split $n ""] {expr $d**[string le $n]}] +]==$n}

Try it online!

Excel, 44 bytes
=A1=SUM(MID(A1,SEQUENCE(LEN(A1)),1)^LEN(A1))

Link to Spreadsheet

Thunno 2, 6 bytes
dDl*S=

Attempt This Online!
Explanation
dDl*S=  # Implicit input     ->  153
d       # Cast to digits     ->  [1, 5, 3]
 Dl     # Push the length    ->  [1, 5, 3]  3
   *    # Exponentiate       ->  [1, 125, 27]
    S   # Sum the list       ->  153
     =  # Equals the input?  ->  1
        # Implicit output

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


text:
Tips for golfing in Bash
What general tips do you have for golfing in Bash? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Bash (e.g. "remove comments" is not an answer). Please post one tip per answer.

Undocumented, but works in every version I've run into for legacy sh backwards compatibility:
for loops allow you to use { } instead of do done.  E.g. replace:
for i in {1..10};do echo $i; done

with:
for i in {1..10};{ echo $i;}

what shell is the is sh and what shell allows this for syntax? it is expressly allowed in zsh.

@mikeserv Bash.  I remember reading somewhere that this syntax was allowed in some old sh and that Bash also allows it because of that, though sadly I don't have a citation.

ahh... csh, probably - that's how they worked in that shell.

by the way, in ksh93 the above thing could be :;{1..10}, and in bash: printf %s\\n {1..10}

for((;i++<10)){ echo $i;} is shorter than for i in {1..10};{ echo $i;}

For arithmetic expansion use $[…] instead of $((…)):
bash-4.1$ echo $((1+2*3))
7

bash-4.1$ echo $[1+2*3]
7

In arithmetic expansions don't use $:
bash-4.1$ a=1 b=2 c=3

bash-4.1$ echo $[$a+$b*$c]
7

bash-4.1$ echo $[a+b*c]
7

Arithmetic expansion is performed on indexed array subscripts, so don't use $ neither there:
bash-4.1$ a=(1 2 3) b=2 c=3

bash-4.1$ echo ${a[$c-$b]}
2

bash-4.1$ echo ${a[c-b]}
2

In arithmetic expansions don't use ${…}:
bash-4.1$ a=(1 2 3)

bash-4.1$ echo $[${a[0]}+${a[1]}*${a[2]}]
7

bash-4.1$ echo $[a[0]+a[1]*a[2]]
7

Replacing while((i--)), which works, with while[i--] or while $[i--] did not work for me. GNU bash, version 4.3.46(1)

Correct, @GlennRanders-Pehrson. That is not supposed to work.

y=\bc<<<"($x*2.2)%10/1"`... example of usingbcfor non-integer calculations... note the/1` at the end truncates the resulting decimal to an int.

s=$((i%2>0?s+x:s+y)) ... example of using ternary operator in bash arithmetic. It's shorter than if..then..else or [ ] && ||

$[ ] is obsolete but still works in some cases. Also, you can increment a counter with just ((i++))

is $[] documented anywhere?  i don't see it in man bash but it works for me.  is it for backwards compatibility?

@Jonah, bash 4.4's man page definitely contains it: https://pastebin.com/zynBK4Ye At least on Ubuntu.

@manatwork Thanks.  They must have removed it.  I'm on GNU bash, version 5.0.2(1)-release (x86_64-apple-darwin16.7.0) and it's not in mine.

Thank you for the information @Jonah. Now I start to appreciate my Ubuntu's inability to upgrade…

The normal, lengthy and boring way to define a function is
f(){ CODE;}

As this guy found out, you absolutely need the space before CODE and the semicolon after it.
This is a little trick I've learned from @DigitalTrauma:
f()(CODE)

That is two characters shorter and it works just as well, provided that you don't need to carry over any changes in variables' values after the function returns (the parentheses run the body in a subshell).
As @jimmy23013 points out in the comments, even the parentheses may be unnecessary.
The Bash Reference Manual shows that functions can be defined as follows:

name () compound-command [ redirections ]

or
function name [()] compound-command [ redirections ]

A compound command can be:

a Looping Construct: until, while or for
a Conditional Construct: if, case, ((...)) or [[...]]
Grouped Commands: (...) or {...}

That means all of the following are valid:
$ f()if $1;then $2;fi
$ f()($1&&$2)
$ f()(($1))                # This one lets you assign integer values

And I've been using curly brackets like a sucker...

Note that you can also use f()while ... f()if ... and other compound commands.

This one surprised me because I thought f()CODE was legal. It turns out that f()echo hi is legal in pdksh and zsh, but not in bash.

its especiallly useful w/ for since it defaults to positionals:f()for x do : $x; done;set -x *;PS4=$* f "$@" or something.

: is a command that does nothing, its exit status always succeeds, so it can be used instead of true.

Using a subshell and piping it would use about the same number of bytes, but piping it would be more practical.

Except when you do :(){:|:}

Well at that point : isn't the same command anymore, this kind of fork bomb just defines a function called : and calls it twice. a(){a|a} is equivalent

More tips

Abuse the ternary operator, ((test)) && cmd1 || cmd2 or [ test ] && cmd1 || cmd2, as much as possible.

Examples (length counts always exclude the top line):
    t="$something"
    if [ $t == "hi" ];then
    cmd1
    cmd2
    elif [ $t == "bye" ];then
    cmd3
    cmd4
    else
    cmd5
    if [ $t == "sup" ];then
    cmd6
    fi
    fi

By using ternary operators only, this can easily be shortened to:
    t="$something"
    [ $t == "hi" ]&&{
    cmd1;cmd2
    }||[ $t == "bye" ]&&{
    cmd3;cmd4
    }||{
    cmd5
    [ $t == "sup" ]&&cmd6
    }

As nyuszika7h pointed out in the comments, this specific example could be shortened even further using case:
    t="$something"
    case $t in "hi")cmd1;cmd2;;"bye")cmd3;cmd4;;*)cmd5;[ $t == "sup" ]&&cmd6;esac

Also, prefer parentheses to braces as much as possible. Since parentheses are a metacharacter, and not a word, they never require spaces in any context. This also means run as many commands in a subshell as possible, because curly braces (i.e. { and }) are reserved words, not meta-characters, and thus have to have whitespace on both sides to parse correctly, but meta-characters don't. I assume that you know by now that subshells don't affect the parent environment, so assuming that all the example commands can safely be run in a subshell (which isn't typical in any case), you can shorten the above code to this:
 t=$something
 [ $t == "hi" ]&&(cmd1;cmd2)||[ $t == "bye" ]&&(cmd3;cmd4)||(cmd5;[ $t == "sup" ]&&cmd6)

Also, if you can't, using parentheses can still minify it some. One thing to keep in mind is that it only works for integers, which renders it useless for the purposes of this example (but it is much better than using -eq for integers).

One more thing, avoid quotes where possible. Using that above advice, you can further minify it. Example:
 t=$something
 [ $t == hi ]&&(cmd1;cmd2)||[ $t == bye ]&&(cmd3;cmd4)||(cmd5;[ $t == sup ]&&cmd6)

In testing conditions, prefer single brackets to double brackets as much as possible with a few exceptions. It drops two characters for free, but it isn't as robust in some cases (it's a Bash extension - see below for an example). Also, use the single equals argument rather than the double. It is a free character to drop.
 [[ $f == b ]]&&: # ... <-- Bad
 [ $f == b ]&&: # ... <-- Better
 [ $f = b ]&&: # ... <-- Best.  word splits and pathname-expands the contents of $f.  Esp. bad if it starts with -

Note this caveat, especially in checking for null output or an undefined variable:
    [[ $f ]]&&:    # double quotes aren't needed inside [[, which can save chars
    [ "$f" = '' ]&&: <-- This is significantly longer
    [ -n "$f" ]&&:

In all technicality, this specific example would be best with case ... in:
    t=$something
    case $t in hi)cmd1;cmd2;;bye)cmd3;cmd4;;*)cmd5;[ $t == sup ]&&cmd6;esac

So, the moral of this post is this:

Abuse the boolean operators as much as possible, and always use them instead of if/if-else/etc. constructs.
Use parentheses as much as possible and run as many segments as possible in subshells because parentheses are meta-characters and not reserved words.
Avoid quotes as much as physically possible.
Check out case ... in, since it may save quite a few bytes, particularly in string matching.

P.S.: Here's a list of meta-characters recognized in Bash regardless of context (and can separate words):
< > ( ) ; & | <space> <tab>

EDIT: As manatwork pointed out, the double parenthesis test only works for integers. Also, indirectly, I found that you need to have whitespace surrounding the == operator. Corrected my post above.
I also was too lazy to recalculate the length of each segment, so I simply removed them. It should be easy enough to find a string length calculator online if necessary.

Sorry to say, but you have some serious errors there. [ $t=="hi" ] will always evaluate to 0, as it is parsed as [ -n "STRING" ]. (($t=="hi")) will always evaluate to 0 as long as $t has non-numerical value, as strings are forced into integers in arithmetic evaluations. Some test cases: http://pastebin.com/WefDzWbL

@manatwork Thanks for the catch. I'll update accordingly.

Using a case would be shorter here. Also, you don't need a space before }, but you do after {.

Why would = be less robust than ==? = is mandated by POSIX, == isn't.

The latter is a Bash extension, but the nonstandard [[ condition ]] is more powerful than [ condition ] but more verbose. I should fix the misinformation, though.

[[ $f ]] is equivalent to [[ "$f" ]].  A [[ context doesn't do word-splitting or pathname expansion, and other expansions don't happen on the result of variable/parameter expansion.  So [[ $f ]] is a good bit shorter than any of the safe alternatives, like [ -n "$f" ].

The question does ask for one tip per answer...

Youv also may want to point out that the [test] && command || command syntax only works like the if statement in some cases, as every section (even the commands) are returning true or false from the pov of the operators.

Avoid $( ...command... ), there is an alternative which saves one char and does the same thing:
` ...command... `

Sometimes $( ) is needed if you have nested command substitutions; otherwise you'd have to escape the inner \``

These technically do different things, I've had to use the backticks instead of $() when I wanted to run the substitution on my machine instead of the scp target machine, for example. In most cases they're identical.

@undergroundmonorail: you never need backticks.  Anything they can do, $() can do if you quote things properly.  (unless you need your command to survive something that munges $ but not backticks).  There are some subtle differences in quoting things inside them.  http://mywiki.wooledge.org/BashFAQ/082 explains some differences.  Unless you're golfing, never use backticks.

@PeterCordes I'm sure there was a way but everything I tried at the time didn't work. Even if backticks weren't the best solution, I was glad I knew about them because it was the only solution I had. ¯\(ツ)/¯

@DigitalTrauma Sample of nesting: echo \bc <<<"\date +%s\\-12"`` ... (It's hard to post sample containing backtick in comment, there! ;)

If you need to pass the content of a variable to STDIN of the next process in a pipeline, it is common to echo the variable into a pipeline.  But you can achieve the same thing with a <<< bash here string:
$ s="code golf"
$ echo "$s"|cut -b4-6
e g
$ cut -b4-6<<<"$s"
e g
$

Since we're golfing, s=code\ golf, echo $s| and <<<$s (keeping in mind that the latter two work only because there are no repeated spaces, etc.).

One-line for loops
An arithmetic expression concatenated with a range expansion will be evaluated for each item in the range. For example the following:
: $[expression]{0..9}

will evaluate expression 10 times.
This is often significantly shorter than the equivalent for loop:
for((;10>n++;expression with n)){ :;}
: $[expression with ++n]{0..9}

If you don't mind command not found errors, you can remove the inital :. For iterations larger than 10, you can also use character ranges, for example {A..z} will iterate 58 times.
As a practical example, the following both produce the first 50 triangular numbers, each on their own line:
for((;50>d++;)){ echo $[n+=d];} # 31 bytes
printf %d\\n $[n+=++d]{A..r}    # 28 bytes

you can also iterate backwards: for((;0<i--;)){ f;}

Oftentimes you can reuse the range in the loop by producing an evalable string. For example, your triangular numbers code could be turned into eval echo\ $[n+={1..50}]\; for 26 bytes

or better yet, eval $[n+={0..50}]\;echo for 24

@JoKing: Although the 24 char version also dumps an error trying to eval the command 0 alone, which the 26 char version avoids.

Instead of grep -E, grep -F, grep -r, use egrep, fgrep, rgrep, saving two chars. The shorter ones are deprecated but work fine.
(You did ask for one tip per answer!)

Too bad there's no Pgrep for grep -P. Although I see how it could be easily confused with pgrep, which is used to look up processes.

@nyuszika7h I personally use grep -o a lot

Wouldn't it save 3 including the space?

A shorter syntax for infinite loops (which can be escaped with break or exit statements) is
for((;;)){ code;}

This is shorter than while true; and while :;.
If you don't need break (with exit as the only way to escape), you can use a recursive function instead.
f(){ code;f;};f

If you do need break, but you don't need exit and you don't need to carry over any variable modification outside the loop, you can use a recursive function with parentheses around the body, which run the function body in a subshell.
f()(code;f);f

Element 0 of an array may be accessed with the variable name only, a five byte saving over explicitly specifying an index of 0:
$ a=(code golf)
$ echo ${a[0]}
code
$ echo $a
code
$

Use arithmetic (( ... )) for conditions
You could replace:
if [ $i -gt 5 ] ; then
    echo Do something with i greater than 5
fi

by
if((i>5));then
    echo Do something with i greater than 5
fi

(Note: There is no space after if)
or even
((i>5))&&{
    echo Do something with i greater than 5
}

... or if only one command
((i>5))&&echo Echo or do something with i greater than 5

Further: Hide variable setting in arithmetic construct:
((i>5?c=1:0))&&echo Nothing relevant there...
# ...
((c))&&echo Doing something else if i was greater than 5

or same
((c=i>5?c=0,1:0))&&echo Nothing relevant there...
# ...
((c))&&echo Doing something else if i was greater than 5

... where if i > 5, then c = 1 (not 0;)

You could save 2 bytes by using [ ] instead of (()) .

@ckjbgames Are you sure of that!? Wich [tag:bash] version are you using?

@FHauri I guess it would be about the same in terms of bytes.

@ckjbgames With [ ] you need the dollar sign for variable. I don't see how you could do same with same or smaller length by using [ ].

Bonus Tip: if the first line of a for loop begins with ((...)), no newline or space is necessary. E.g. for((;10>n++;)){((n%3))&&echo $n;} Try it online!

@primo I already used this at ip2int IPv4 integer challenge. Read my last purpose, with 68 chars,  using mapfile!

@F.Hauri I was surprised that it works ({ followed by anything else seems to require whitespace), and hadn't seen this mentioned anywhere, so I thought it would be a good addition to your tip.

Loop over arguments
As noted in Bash “for” loop without a “in foo bar…” part, the in "$@;" in for x in "$@;" is redundant.
From help for:
for: for NAME [in WORDS ... ] ; do COMMANDS; done
    Execute commands for each member in a list.

    The `for' loop executes a sequence of commands for each member in a
    list of items.  If `in WORDS ...;' is not present, then `in "$@"' is
    assumed.  For each element in WORDS, NAME is set to that element, and
    the COMMANDS are executed.

    Exit Status:
    Returns the status of the last command executed.

For example, if we want to square all numbers given positional arguments to a Bash script or a function, we can do this.
for n;{ echo $[n*n];}

Try it online!

Use if to group commands
Compared to this tip which removes the if at all, this should only work better in some very rare cases, such as when you need the return values from the if.
If you have a command group which ends with a if, like these:
a&&{ b;if c;then d;else e;fi;}
a&&(b;if c;then d;else e;fi)

You can wrap the commands before if in the condition instead:
a&&if b;c;then d;else e;fi

Or if your function ends with a if:
f(){ a;if b;then c;else d;fi;}

You can remove the braces:
f()if a;b;then c;else d;fi

You could use the ternary operator [test] && $if_true || $else in these functions and save some bytes.

Also, you don't need spaces around && and ||

Use [ instead of [[ and test when possible
Example:
[ -n $x ]

Use = instead of == for comparison
Example:
[ $x = y ]

Note that you must have spaces around the equals sign or else it won't work. Same applies to == based on my tests.

The [ vs. [[ may depend on the amount of required quotes: http://pastebin.com/UPAGWbDQ

@manatwork That's a good point.

General rule: [...] == /bin/test, but [[...]] != /bin/test and one should never prefer [...] over [[...]] outside of codegolf

tr -cd is shorter than grep -o
For example, if you need to count spaces, grep -o <char> (print only the matched) gives 10 bytes while tr -cd <char> (delete complement of <char>) gives 9.
# 16 bytes
grep -o \ |wc -l
# 15 bytes
tr -cd \ |wc -c

(source)
Note that they both give slightly different outputs. grep -o returns line separated results while tr -cd gives them all on the same line, so tr might not always be favourable.

To concatenate lines, instead of tr -cd \\n you can do rs -g0

Shorten file names
In a recent challenge I was trying to read the file /sys/class/power_supply/BAT1/capacity, however this can be shortened to /*/*/*/*/capac*y as no other file exists with that format.
For example, if you had a directory foo/ containing the files foo, bar, foobar, barfoo and you wanted to reference the file foo/barfoo, you can use foo/barf* to save a byte.
The * represents "anything", and is equivalent to the regex .*.

Alternative to cat
Say you are trying to read a file and use it in something else. What you might do is:
echo foo `cat bar`

If the contents of bar was foobar, this would print foo foobar.
However, there is an alternative if you are using this method, which saves 3 bytes:
echo foo `<bar`

Is there a reason why <bar by itself does not work but placing it in backticks does?

@Cowsquack Yes. The < puts a file to a command, but in this case it puts it into standard output due to a quirk. The backticks evaluate this together.

Is there a shorter way to read from standard input other than \cat``?

@Joel dd can do sometimes

Sometimes it is shorter to use the expr builtin for displaying the result of a simple arithmetic expression instead of the usual echo $[ ].  For example:
expr $1 % 2

is one byte shorter than:
echo $[$1%2]

Use tail recursion to make loops shorter:
These are equivalent in behavior (though probably not in memory/PID usage):
while :;do body; done
f()(body;f);f
body;exec $0
body;$0

And these are roughly equivalent:
while condition; do body; done
f()(body;condition&&f);f
body;condition&&exec $0
body;condition&&$0

(technically the last three will always execute the body at least once)
Using $0 requires your script to be in a file, not pasted into the bash prompt.
Eventually your stack might overflow, but you save some bytes.

Alternatives to head
line is three bytes shorter than head -1, but is being deprecated.
sed q is two bytes shorter than head -1.
sed 9q is one byte shorter than head -9.

Although doomed, we can still use for a while line from util-linux package to read a single line.

Use a pipe to the : command instead of /dev/null. The : built-in will eat all its input.

No, it will crash the program with SIGPIPE in most cases. echo a|tee /dev/stderr|: will not print anything.

There is a race: echo a|tee /dev/stderr|: did print a on my computer, but elsewhere SIGPIPE might kill tee first. It might depend on version of tee.

Yes, it's a SIGPIPE problem: tee >(:) < <(seq 1 10) will work, but tee /dev/stderr | : won't. Even a() { :;};tee /dev/stderr < <(seq 1 10)| a don't print anything.

@user16402 - you should have a fccing name to my purview... anyway, the : intrinsic eats not at all... if you supposit input to colon you might flood a pipe to in out error... but you can float a redirect by a colon, or drop a process with it... :| while i>&$(($??!$?:${#?})) command shit; do [ -s testitsoutput ]; done or however that pseudo suggestion applies... also, are you aware youre nearly so ghosty as me?  ... avoid at all costs the < <(psycho shit i can alias to crazy math eat your world; okay? anyway, ksh93 has a separate but equal composite char placement)

split has another (deprecated, but nobody cares) syntax for splitting input into sections of N lines each: instead of split -lN you can use split -N e.g. split -9.

Expand away the tests
Essentially, the shell is a kind of macro language, or at least a hybrid or some kind. Every command-line can be basically broken into two parts: the parsing/input part and the expansion/output part.
The first part is what most people focus on because it's the most simple: you see what you get. The second part is what many avoid ever even trying to understand very well and is why people say things like eval is evil and always quote your expansions - people want the result of the first part to equal the first. That's ok - but it leads to unnecessarily long code branches and tons of extraneous testing.
Expansions are self-testing. The ${param[[:]#%+-=?]word} forms are more than enough to validate the contents of a parameter, are nestable, and are all based around evaluating for NUL - which is what most people expect of tests anyway. + can be especially handy in loops:
r()while IFS= read -r r&&"${r:+set}" -- "$@" "${r:=$*}";do :;done 2>&-

IFS=x
printf %s\\n some lines\ of input here '' some more|{ r;echo "$r"; }

somexlines ofxinputxhere

...while read pulls in not blank lines "${r:+set}" expands to "set" and the positionals get $r appended. But when a blank line is read, $r is empty and "${r:+set}" expands to "" - which is an invalid command. But because the command-line is expanded before the "" null command is searched, "${r:=$*}" takes the values of all of the positionals concatenated on the first byte in $IFS as well. r() could be called again in |{ compound command ;} w/ a different value for $IFS to get the next input paragraph as well, since it is illegal for a shell's read to buffer beyond the next \newline in input.

Use pwd instead of echo to generate a line of output
Need to put a line on stdout but don't care about the contents, and want to restrict your answer to shell builtins? pwd is a byte shorter than echo.

id is even shorter.

w for the win?

Quotes can be omitted when printing strings.
echo "example"
echo example

Output in SM-T335 LTE, Android 5.1.1:
u0_a177@milletlte:/ $ echo "example"
example
u0_a177@milletlte:/ $ echo example
example

Abuse function definitions to check for equality
If you want to check if two strings are equal to each other, the obvious way is to use the [[/test/[ builtins:
[[ $a == b ]]
[[ $a = b ]]
[ $a = b ]

But in fact often a shorter way is to define a do-nothing function under the name of b and then try to call it with $a.
b()(:);$a
# zsh only:
b():;$a

Depending on the possible values $a can take, you might need to add some  characters to ensure that it never coincides with the name of a real command:
,b()(:);,$a
# zsh only:
,b();,$a

If you're testing and immediately using &&, then you can put generally put the command after the && as the body of the function:
[ $a = b ]&&foo
b()(foo);$a
# zsh only:
b()foo;$a

Here are a few answers I've abused this in (Zsh not Bash, but the same idea applies):

https://codegolf.stackexchange.com/a/219018
https://codegolf.stackexchange.com/a/219167

you can also do ${a/$b} and check if the result is an empty string

Output a string based on a test string or numeric test with expr
From my question:
For any form of test expr supports (numerical or string equality, inequality, less than, greater than, regex pattern match, with support for math), there are often ways to use it to improve on the naive approach to echoing a particular string based on a given test. For example, the most straightforward approach to performing an "is a program argument a substring of a fixed string?" test, echoing the string true or false based on the result, assuming the substring contains no regex special characters, is:
[[ FIXEDSTRING =~ $1 ]]&&echo true||echo false

But with expr, we can shave off six characters by careful use of & and | to select the string that results from the overall test:
expr true \& FIXEDSTRING : .*$1 \| false

Changing the * to \* (and costing a character) if there is a possibility that the command will be run in a directory where .*$1 would match existing files.
The ordering is important here; \& evaluates to the first argument (not the second like in Python and similar language) when the overall "and" expression is true, so true \& must come before the pattern match test FIXEDSTRING : .*$1. The .* is needed because pattern matching is implicitly anchored at the beginning, as with ^, so the .* lets it match anywhere. And no, sadly, you can't remove any of these spaces; expr expects each operand and operator to be a completely separate argument, so it doesn't need to do any tokenizing of its own, which means the spaces must be there so the shell can tokenize it.
For the specific case of a regex match, you can shorten it four more characters with sed, :
sed "/$1/ctrue
cfalse"<<<FIXEDSTRING

Similar uses allow replacing the various forms of numerical test and echo:
[ $1 -gt 0 ]&&echo yes||echo no
[[ $1>0 ]]&&echo yes||echo no
(($1>0))&&echo yes||echo no

with:
expr yes \& $1 \> 0 \| no

which, even with the need to escape the >, and despite numerical tests with (()) allowing you to drop all whitespace, is still two characters shorter than the shortest of the naive approaches. If the comparison is more complex, you can mix-and-match:
expr yes \& $[$1>0] \| no

is the same length as the purely expr-based approach, but grows more slowly in more complex cases (as fewer things need escaping, and spaces aren't needed between terms).

When assigning noncontinuous array items, you can still skip the successive indices of continuous chunks:
bash-4.4$ a=([1]=1 [2]=2 [3]=3 [21]=1 [22]=2 [23]=3 [31]=1)

bash-4.4$ b=([1]=1 2 3 [21]=1 2 3 [31]=1)

The result is the same:
bash-4.4$ declare -p a b
declare -a a=([1]="1" [2]="2" [3]="3" [21]="1" [22]="2" [23]="3" [31]="1")
declare -a b=([1]="1" [2]="2" [3]="3" [21]="1" [22]="2" [23]="3" [31]="1")

According to man bash:

Arrays are assigned to using compound assignments of the form name=(value1 ... valuen), where each value is of the form [subscript]=string. Indexed array assignments do not require anything but  string. When assigning to indexed arrays, if the optional brackets and subscript are supplied, that index is assigned to; otherwise the index of the element assigned is the last index assigned to by the statement plus one.

Helpful to add: uninitialised elements will expand to 0 in arithmetic expansions and "" in other expansions.

Print the first word in a string
If the string is in the variable a and doesn't contain escape and format characters (\ and %), use this:
printf $a

But it would be longer than the following code if it is needed to save the result into a variable instead of printing:
x=($a)
$x

It is almost always better to receive input as arguments to a script or function instead of on stdin. Examples:
Input: a string:
# == stdin ==
read a;echo $a
echo `<&0`
# == arguments ==
echo "$1"       # if $1 can have globbing characters/newlines/tabs
echo $1         # if $1 does not have any problematic characters

Input: a list of strings:
# == stdin ==
while read s; do echo $s; done          # one-time use, split on newlines
read -a a;for s in ${a[@]};{echo $s;}   # read one line from stdin; splits on spaces
mapfile a;for s in "${a[@]}";{echo $s;} # read to EOF, split on newlines
# == arguments ==
for s;{ echo $s;}

The exception: a list of strings and other arguments:
read i;while read s; do echo ${s[$i]}; done   # both on stdin
i=$1;shift;for s;{ echo ${s[$i]};}            # both as arguments
read i;for s;{ echo ${s[$i]};}                # list as arguments, other as stdin

Additionally, read will mangle backslashes without -r, and will stop on newlines without -d '', making it even more expensive in worst case scenarios.

Read lines l from a file p, in Zsh: for l ("${(f)$(<p)}")

In Pure Bash (or any other pure shellscript), use . for looping.
For example, if you want to display each value of 1^2, 2^2, 3^2, ..., 999^2, 1000^2,
echo $[++x*x]
((x>999))||. x

(where filename is x) is shorter than
for((;x++<1000;));{
echo $[x*x]
}

Try it online!

I noticed this can be applied to non-pure shell script too.

Use $_ (the underscore variable)
The special shell variable $_ always contains the last argument to the most recently executed command. If you have any sort of immediate repetition in your code, it can probably be reduced with this.
touch hello;cat hello
touch hello;cat $_

More details can be found in this Unix & Linux question.
(I can't believe this hasn't been posted before, and, as far as I can tell, barely ever even been used in code golf before!)

$_ isn't reliably populated, for example in case $_ it's empty

Know grep options
See also man 1p grep and manual for GNU Grep.
grep -x foo is equivalent to grep '^foo$
This is POSIX-compatible.

Consider only input lines that use all characters in the line excluding the terminating <newline> to match an entire fixed string or regular expression to be matching lines.

For example, the following two are equal:

grep -E '^abc$|^def$'

grep -F -x 'abc
def'

Doing 2 embed loop with 1 for instruction:
for ((l=i=0;l<=99;i=i>98?l++,0:++i)) ;do
    printf "I: %2d, L: %2d\n" $i $l
done |
    tee >(wc) | (head -n4;echo ...;tail -n 5)
I:  0, L:  0
I:  1, L:  0
I:  2, L:  0
I:  3, L:  0
...
I: 96, L: 99
I: 97, L: 99
I: 98, L: 99
I: 99, L: 99
  10000   40000  130000

In a case statement, it is valid to omit the last ';;' - which saves 2 bytes:
#!/bin/sh

case $I in
0)cmdA;;
1)cmdB;;
*)cmdC
esac

Assign and Print quoted strings
If you want to assign a quoted string to a variable, and then print the value of that variable, then the usual way to do that would be:
a="Programming Puzzles & Code Golf";echo $a

If a was previously unset, this may be shortened to:
echo ${a=Programming Puzzles & Code Golf}

If a was previously set, then this should be used instead:
echo ${a+Programming Puzzles & Code Golf}

Note this is only useful if the string requires quotes (e.g. contains whitespace).  Without quotes, a=123;echo $a is just as short.

${a+foo} doesn't set a.

Use {..} expansions with eval
Occasionally loops can be shortened by using eval with a brace expansion. For example, to run a command foo with all letters a-z sequentially; instead of:
for x in {a..z};{ foo $x;}
# or, zsh only:
for x ({a..z})foo $x

eval foo\ {a..z}\;
# or, zsh only:
eval ';foo '{a..z}

If you need to reuse the loop variable, it tends to be shorter to use a normal for-loop though.
I can't remember exactly the first answer I saw to do this, but I now use it a lot (those examples are all Zsh because it's obviously superior to Bash, but it's a similar general idea).

Compress long runs of decimal digits using alternate base representation
bash's arithmetic context supports numbers in arbitrary alternate bases more compactly that any other language I know of (e.g. Python's int(string,base) has overhead of five characters for the int, (, ), and ,, if you aren't given the string from elsewhere, two more for the ' or " around the literal, plus 1-2 characters for the base). By contrast, bash only needs three characters to impose arithmetic context, $[] (if you're not already in it), and just one character to impose alternate base context, and the same 1-2 characters for the base, so bash needs 2-6 characters to do what Python (which is relatively good on this score) needs 6-9 characters to do.
Bash also supports higher bases for integer literals than most languages (topping out at base 64, rather than base 36 as is common; if you use a base above 36, it uses a digit "alphabet" of up to 0-9a-zA-Z@_).
Between these two features, you can shave up to three characters off long strings of decimal digits by replacing them with arithmetic context (using the shorter form of arithmetic expansion) of a base 64 value. The best savings occur when the digits in question require an even multiple of six bits to represent in binary, and no savings are available unless the decimal representation of the integer is at least 15 characters long, but when it works, it's a great way to shorten further. If you're using it as a number in an existing arithmetic context that does other math, you can save up to 6 characters (since the $[] is already paid for by the need to do math, so it doesn't count against the cost of the alternate base), and benefits begin to appear at just 8 decimal digits.
For the best case scenario, a program that needs a literal string numerically equivalent to a number between (with _ for readability)
1_000_000_000_000_000_000 and 1_152_921_504_606_846_975 can represent such a number as either:
1000000000000000000
# or shaving three characters
$[64#TwJHeDp000]

If you were already in arithmetic context, it saves six instead:
$[var%1000000000000000000]
# becomes
$[var%64#TwJHeDp000]

This work under simple shell
cd `mktemp -d` &&>'c'a't'
ln -s /proc/loadavg /proc/uptime .

Then now
procs=$(*)
echo $procs
0.30 0.08 0.03 1/612 31671 322787.60 1259967.99

Nota: Of course, >cat could be written >$(echo -e \\0143\\0141t)
Care, from there, you could encouter some issues due to Locales!
Goto last demo using LC_ALL=C
Same way:
mv cat grep
mv loadavg Mem
ln -s /proc/meminfo Zdatas
rm uptime

mems=$(*)
echo $mems
MemTotal: 16386788 kB MemFree: 9816320 kB MemAvailable: 12144892 kB

or worst...
mv grep sed
mv Mem s+\\\(Mem\\\|Swap\\\).\*\:++p\;d

then
memsw=$(*)
echo $memsw
16386788 kB 9834080 kB 12163596 kB 0 kB 20971516 kB 20971516 kB

So simple is this!
declare -p procs mems memsw
declare -- procs="0.14 0.12 0.05 1/612 32078
324221.56 1265616.26"
declare -- mems="MemTotal:       16386788 kB
MemFree:         9832212 kB
MemAvailable:   12161688 kB"
declare -- memsw="       16386788 kB
         9834080 kB
   12163596 kB
            0 kB
      20971516 kB
       20971516 kB"

Last test using LANG=C
(or not)
cd `mktemp -d` &&>'c'a't'
ln -s /proc/meminfo zdatas
cp c* y+-+-+\;s+\\\(Mem\\\|Swap\\\).\*\:\ \*++p\;d
rename 'y/act/esd/' ???
*

may render something like
378908 kB
31940 kB
217924 kB
0 kB
102396 kB
102396 kB

Or
cd `mktemp -d`
ln -s +++\;s+\\\(Mem\\\|Swap\\\).\*\:\ \*++p\;d /proc/me*o ed .
rename 's/^/chr(113+(20>length?1.3*length:8))/e' *
*

or printf -vv %b \\014{3,1} t&&>$v under [tag:bash]

Changing behaviour of += by setting integer flag
Try this many times:
unset i
i=1
for a in {1..10} ;do
    i+=1
    ((RANDOM%9)) || declare -i i
  done
echo $i
11117

or in one line
unset i;i=1;for a in {1..10};do i+=1;((RANDOM%9))||declare -i i;done;echo $i

This could answer something between 20 to 11111111111...

To print a range of characters (shorter than echo {a..z}|tr -d ' '):
printf "%s" {a..z}

Print range in reverse order (shorter than printf "%s" {a..z}|rev):
printf "%s" {z..a}

Why not echo {a..z} ?

ONE-LINE CONDITIONAL SETTER
NOTE: I see now that this first bit is already present on the first page, so I updated to add another tip (below the phrase 'EDIT-POINT:') which adds to the initial syntax to achieve a different outcome.
Here is a super efficient way to do control statements in bash.
instead of
if [ -e "${var}" ]
then
   echo "${var}"
else
   echo "empty"
fi

which translates to the one-liner:
if [ -e "${var}" ]; then echo "${var}"; else echo "empty"; fi

...you can use logical and / or like so:
[ -e "${var}" ] && echo "${var}" || echo "empty"

The second bit runs only if the first bit returns a 0 exit code. If either of the first two bits fail to exit with 0 (in other words, if false when used with [] / test command), the third bit runs. This means that in production / distribution use cases, this form is often a bad idea (if the if logic runs but fails fails, the else statement runs..), but for code golf, it is ore than sufficient, so long as you test it on the command line first.
It also works with the if / && (no else / ||), e.g.
[ -e "${var}" ] && echo "${var}"

if that is what you need. This version runs exactly as the long form, without the caveat mentioned above.
EDIT-POINT:
Another advantage of using this syntax is that you can put the entire command inside a variable. When you need to set a variable to a value that is based on a condition, this saves a lot of space.
For example,
if [ -e "${var}" ]
then
   TEXT="${var}"
else
    TEXT="empty"
fi

can be dropped to:
TEXT=$([ -e "${var}" ] && echo "${var}" || echo "empty")

As a code golf tip, this has limited uses, but they do exist. The space gained or lost depends on the size of the variable name. It adds up to the same as setting a four-letter variable (so ends in unity in the example above.)
Since we use single-letter variable names in code golf, this normally doesn't save any space at all. The space saving effect kicks in when we have no control over the name, in cases where we are using an environment variable in a cheeky way, or when a variable name is provided via a constraint in the question.

-1 because duplicated.

@nrgmsbki4spot1 Thank you for commenting. I didnt even notice there were 2 pages. Deleting, but I will wait a few hours so you have time to see comment / thank you. I know thank yous are looked down upon in some of the sites, but for me, they are my favorite part, and honestly, they are what keeps me coming back. On that note, thanks again.

@nrgmsbki4spot1 Decided to edit instead. Added Another 'trick' which builds on the original. I left the original bit, as the new one wouldn't make much sense without it. Is this better?

As the first tip was previously included, I would assume that I am okay in the way of "one tip per answer", and I do feel it adds value. Sorry to bother you again. I am new to this SE, so I am still learning the sites nuances. Btw, if your wondering how someone could miss the first page altogether, its because I found it via link.

source: Stack Exchange

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

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

sort: votes


text:
Obtaining ordering of cards
You are given a deck containing n cards.  While holding the deck:

Take the top card off the deck and set it on the table
Take the next card off the top and put it on the bottom of the deck in your hand.
Continue steps 1 and 2 until all cards are on the table.  This is a round.
Pick up the deck from the table and repeat steps 1-3 until the deck is in the original order.

Write a program to determine how many rounds it will take to put a deck back into the original order.
I found some answers online that had answers online for comparing and I cannot get the same answers. Either they are wrong or I am completely wrong. I went through a few examples of my own got these answers:
5 cards:
    order: 12345
1: 24531
2: 43152
3: 35214
4: 51423
5: 12345   <-- 5 rounds

6 cards:
order: 123456
1: 462531
2: 516324
3: 341265
4: 254613
5: 635142
6: 123456   <-- 6 rounds

Answers I found online were:
Problem: http://www.velocityreviews.com/forums/t641157-solution-needed-urgent.html
Answer: http://www.velocityreviews.com/forums/t641157-p2-solution-needed-urgent.html   <-- last post

I found another solution that has the same solution as mine but not sure on any solutions credibility:
http://entrepidea.com/algorithm/algo/shuffleCards.pdf

I was wondering if anyone has done this problem before and would be able to confirm which answers are correct. I need something to test against to see if my program is giving the correct output. THANKS!

Python
def game(a):
    deck = range(1,a+1)
    #store the deck
    origDeck = []
    #copy the deck
    origDeck.extend(deck)
    table =[]
    ans = 0
    while 1:
        while len(deck) > 0:
            table.append(deck.pop(0))
            if len(deck) == 0:
                break
            deck.append(deck.pop(0))
        table.reverse()
        deck,table=table,deck
        ans+=1
        #this is the condition that exits the infinite loop
        if deck==origDeck:
            break
    print ans

Calling game(n) prints the number of rounds for n cards. The code can be easily changed to allow for printing the deck between rounds (add print deck before if deck==origDeck).

Tests (1 through 50):
1: 1
2: 2
3: 3
4: 2
5: 5
6: 6
7: 5
8: 4
9: 6
10: 6
11: 15
12: 12
13: 12
14: 30
15: 15
16: 4
17: 17
18: 18
19: 10
20: 20
21: 21
22: 14
23: 24
24: 90
25: 63
26: 26
27: 27
28: 18
29: 66
30: 12
31: 210
32: 12
33: 33
34: 90
35: 35
36: 30
37: 110
38: 120
39: 120
40: 26
41: 41
42: 42
43: 105
44: 30
45: 45
46: 30
47: 60
48: 48
49: 120
50: 50

31 produces a peculiar output; it goes through 210 rounds.
It appears that primes have large cycles. For example, 97 has the largest cycle under 100: 6435.

Haskell
The way of handling cards is somewhat problematic, the code for turn became rather complex.
But finally both the cases for 5 and 6 match.
import Data.List
import Control.Arrow

spl :: [a] -> ([a],[a])
spl = (map snd***map snd) . partition ((==1).(`mod`2).fst) . zip [1..]

turn :: [a] -> [a]
turn' :: [a] -> [a] -> [a]
turn x = reverse $ turn' x []
turn' [] []       = []
turn' [] ls       = turn' (reverse ls) []
turn' [x] []      = [x]
turn' [x] ls      = turn' (x:(reverse ls)) []
turn' (x:y:ys) ls = x : (turn' ys (y:ls))

cardCycle x = first : (takeWhile (/=first) $ iterate turn (turn first))
  where first = [1..x]

ans = length . cardCycle

main = mapM_ (\x -> putStrLn ((show x) ++ ": " ++ (show (ans x)))) [1..20]

.
1: 1
2: 2
3: 3
4: 2
5: 5
6: 6
7: 5
8: 4
9: 6
10: 6
11: 15
12: 12
13: 12
14: 30
15: 15
16: 4
17: 17
18: 18
19: 10
20: 20

16 seems to be an interesting one so here's the cycle (layout added):
> cardCycle 16
[[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
,[16,8,12,4,14,10,6,2,15,13,11,9,7,5,3,1]
,[1,2,9,4,5,13,10,8,3,7,11,15,6,14,12,16]
,[16,8,15,4,14,7,13,2,12,6,11,3,10,5,9,1]]

Sorry but I don't think you did. A deck with 4 cards takes 2 rounds. 1234 (1 on top) --> 4231 --> 1234. Nice try! I appreciate your effort!

Ah, true. I only laid every other card on the table and left the others in hand. Once half the cards were on the table I put them on the bottom and started again. I will have to take a look if I can correct this.

Pure Bash
It is not clear in your question (unless I missed it) if when you put a card on the table you put it above or below the cards already there. Here are two versions, and you'll see that the answer differs:
Cards above
orig="12345"
deck=$orig
table=

nb=0

play() {
    ((++nb))
    while [[ -n $deck ]]; do table=${deck:0:1}$table; deck=${deck:2}${deck:1:1}; done
    deck=$table
    table=
    echo "$nb: $deck"
}

while ((nb==0)) || [[ $deck != $orig ]]; do play; done

this yields:
1: 24531
2: 43152
3: 35214
4: 51423
5: 12345

Cards below
Replace play with:
play() {
    ((++nb))
    while [[ -n $deck ]]; do table+=${deck:0:1}; deck=${deck:2}${deck:1:1}; done
    deck=$table
    table=
    echo "$nb: $deck"
}

which yields:
1: 13542
2: 15243
3: 12345

Golfed versions, reading input on stdin

Below:
read o;d=$o;t=;n=0;p(){((++n));while [[ $d ]];do t+=${d:0:1};d=${d:2}${d:1:1};done;d=$t;t=;echo $d;[[ $d = $o ]]||p; };p;echo $n

Above:
read o;d=$o;t=;n=0;p(){((++n));while [[ $d ]];do t=${d:0:1}$t;d=${d:2}${d:1:1};done;d=$t;t=;echo $d;[[ $d = $o ]]||p; };p;echo $n

You can infer from the question that the cards are placed above. See the example for five cards.

@Quincunx that's right... but that might also be a source of confusion. That's why I explicitly mentioned it and gave the two possibilities.

Mathematica
shuffleTillUnshuffled[
  n] takes a deck of n cards and shuffles it until it returns to the
original order.
playRound takes a deck and returns the reordered deck of cards
after one round of shuffling.
rule1 places the top card on the table and the second card at the
bottom of the deck.
rule2 places the last card of the deck onto the table.
[[2]], that is, Part[{inHand,onTable},2] removes the deck from the table so that it can be used, if
still unordered, in the next round.
rule1={{s_,m1_,e___},{l___}}:> {{e,m1},{s,l}};
rule2={{s_},{e__}}:> {{},{s,e}};
playRound[deck_]:=({deck,{}}//.{rule1,rule2})[[2]]
shuffleTillUnshuffled[nCards_]:=  {rr=RotateRight[NestWhileList[playRound[#]&,playRound@Range@nCards,!OrderedQ[#]&]];
"Deck size: "<>ToString@nCards<>" cards; Rounds: "<>ToString@Length[rr],rr//Grid}

shuffleTillUnshuffled[4]
shuffleTillUnshuffled[5]
shuffleTillUnshuffled[13]

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


text:
TUT language translator
Text may be translated to a written version of TUT language by replacing each letter by the corresponding "TUT word", as given in the following table (adapted from the linked article)*:
a  e        h  hash     o  o        u  yu
b  bub      i  ay       p  pup      v  vuv
c  kut      j  jag      q  kwak     w  waks
d  dud      k  kak      r  rut      x  eks
e  i        l  lul      s  sus      y  yak
f  fuf      m  mum      t  tut      z  zuz
g  jug      n  nun

* Exceptions:
(1) Upper case letters have corresponding TUT words in upper case.
(2) A doubled letter becomes 'skwer' ('SKWER') followed by the TUT word for that letter.
    - An n-fold letter is treated as a number of doubles, followed by a single if needed.
    - To be considered a double or n-fold letter, the letters must be in the same case.
(3) 'rut' ('RUT') is replaced by 'rud' ('RUD') if immediately followed by 'dud' ('DUD').

Write a program with the following i/o behavior:
Input (from stdin): A binary (0/1) indicator i and an ASCII string s.

If i = 0 then s may contain any ASCII text.
If i = 1 then s must be the TUT Language output for some valid input.

Output (to stdout): A binary (0/1) indicator j and an ASCII string t.

If i = 0 then j = 1 and t is the translation of s to TUT Language.
If i = 1 then j = 0 and t is the translation of s from TUT Language.
For any valid input, applying the program to its own output must exactly reproduce the original input; i.e., program (program (i, s)) = (i, s). Input and output must have exactly the same format.

Scoring: The score is the number of characters in the program -- lowest score wins.
Examples
(a)
(0, 'Look for the birds.')
(1, 'LULskwerokak fuforut tuthashi bubayruddudsus.')

(b)
(0, '"Mrs. Hogwallop up and R-U-N-N-O-F-T."')
(1, '"MUMrutsus. HASHojugwakseskwerlulopup yupup enundud RUT-YU-NUN-NUN-O-FUF-TUT."')

(c)
(0, 'QWX WWW Rrrrd deeeeep')
(1, 'KWAKWAKSEKS SKWERWAKSWAKS RUTskwerrutruddud dudskweriskweriipup')

(d)
(0, 'aa AA aA Aa rd RD rD Rd')
(1, 'skwere SKWERE eE Ee ruddud RUDDUD rutDUD RUTdud)

(((Aside about pronunciation: The TUT words for the vowels (e, i, ay, o, yu) are supposed to represent the usual sounds of (a, e, i, o, u) when reciting the alphabet -- i.e., rhyming with (may, me, my, mow, mew). In the three-or-more-letter TUT words, the symbols (u,a,e) are supposed to sound as in (but, bat, bet) respectively -- these are ASCII replacements for (ʌ æ ɛ)  in the linked article.)))

do we have to support doubled uppercase? What's the tut translation of AA, SKWERE or skwerE? What about tripled letters? is it wakswakswaks, skwerwakswaks, waksskwerwaks, or even kyubwaks, or we may choose?

rrd should translate to skwerruddud; are we allowed to leave it at skwerrutdud?

@JanDvorak - Yes, it should handle doubled letters, regardless of case. Input (0,'AA SKWERE skwerE') should have output(1,'ee SUSKAKWAKSIRUTI suskakwaksirutI'). Inputs (1,'AA') and (1,'skwerE') are not valid because 'AA' and 'skwerE' do not occur as outputs of any valid input. Input (1, 'SKWERE') should have output (0,'EE'). A string of three or more letters should be regarded as some number of doubles, possibly followed by a single. Input (0,'rrd') should have output (1,'skwerruddud').

uh... how does 0,"AA" translate to 1,"ee"? As for 1,"SKWERE", I assume you meant 0,"AA", not 0,"EE".

@JanDvorak - Sorry, my bad: input (0,'AA SKWERE skwerE') should have output (1,'SKWERE SUSKAKWAKSIRUTI suskakwaksirutI'), and input (1, 'SKWERE') should have output (0,'AA'). I hope I got it right this time ... When I can manage to keep it straight myself, I'll edit the question :)

OK... is my answer correct, then? :-)

@JanDvorak -- See my reply to your answer.

Shouldn't LULskwerokut read LULskwerokak in the output of the first example?

@DavidCarraher -- Indeed it should; thanks ... fixing.

Heh, this question has more naughty Dutch words than usual :P

@r.e.s. I need 2 clarifications because I'm confused! 0,Rd should return 1,RUTdud or 1,RUDdud? 0,AA should return 1,skwerE or 1,SKWERE.

@psxls - I intended (0,rd_RD_rD_Rd) -> (1,ruddud_RUDDUD_rutDUD_RUTdud) and (0,aa_AA_aA_Aa) -> (1,skwere_SKWERE_eE_Ee). Rule (3) applies to the TUT words 'skwere' and "SKWERE'.

I reorganized the list of exceptions and added an example to clarify the above points.

In Polish, Skwer means square, place, usually green :)

this challenge kinda sus

Ruby, 310 311 characters
h=Hash[(?a..?z).zip %w{e bub kut dud i fuf jug hash ay jag kak lul mum nun o pup kwak rut sus tut yu vuv waks eks yak zuz}]
h["rd"]="ruddud"
h.keys.each{|k|h[k[0]+k]="skwer"+h[k]}
h.keys.each{|k|h[k.upcase]=h[k].upcase}
h=h.invert if b=getc==?1
i=gets
print b ?0:1;(k=i;k=k.chop until h[k]||!k[1];$><<(h[k]||k);i[k]="")until i==""

Correctly handles:

squared uppercase (unfix by merging iterations gains 18 characters)

if AA should turn into skwerE, swap lines #3 and #4
I also assume aA and Aa should turn into eE and Ee respectively

rrd translates to `skwerruddud (unfix gains 3 characters)
in cubes the first pair is reported as a square. rrrd turns into skwerrutruddud. rrrrd becomes skwerrutskwerruddud
the output is now a valid input. It is, indeed, required by the spec
uses newline as input terminator

Input requires there be no newline between the indicator and the string, output puts it there (fix: 1 character). Console output suppressed at this point to prevent mixing with STDIN. Unfix free, it's just a little bit uglier.
Example input:
0Hello

Output:
1
HASHiskwerlulo

I was vacillating about whether to require input & output to have identical formats, but it wasn't clear in the question, so ... this answer looks fine to me (so far -- I'll run some tests on the answers soon).

I don't know why, but your program runs for me -- both online and off -- only if getc is prefixed with STDIN. (six more characters).

I'm using jRuby IRB 1.7.5 (2.0.0) and it shows me only a warning. What verion are you using?

I like the shorthand to create the map. I just included it fully. Which makes it unlikely that I will beat that.

@r.e.s. I believe that the input/output requirement was clear: For any valid input, applying the program to its own output must exactly reproduce the original input; i.e., program (program (i, s)) = (i, s). But it would only cost 1 character to fix that.

Thanks Jan. My program could be 4 characters smaller if I don't add a newline. Wait. I can read a single character for the cost of 2 extra characters...

@JanDvorak - I'm using Ruby 1.9.3 from www.ruby-lang.org (as does Ideone.com). I suppose it's time to upgrade.

@JohannesKuhn - The question is whether "exactly reproduce" may in some degree refer to content rather than exclusively to format, and I gave Jan the benefit of the doubt over the presence/absence of a single newline.

The point is that the output should be a possible input format, so cat input | prog | prog should work at least.

@JohannesKuhn - Point taken. Apparently Jan agrees, since he revised his program accordingly. I will clarify this in the question.

Jan - you've revised your program, but not your example output (it still has the newline). Also, I just upgraded to Ruby 2.0.0, and still your program won't run for me unless getc is replaced with STDIN.getc. (I'm using echo 0Hello | ruby tut.rb.)

@JanDvorak Very nice +1. But it fails at 0Rd.

@psxls Depends on the interpretation. If you say that it contains 2 rules or any combination of them.

@JanDvorak You was right, r.e.s. just clarified the situation. I'll have to change my own answer...!

Perl, 453 443 309 307 303 299
($x,$_)=split//,<>,2;@x{a..z,rd}=(e,bub,kut,dud,i,fuf,jug,hash,ay,jag,kak,lul,mum,nun,o,pup,kwak,rut,sus,tut,yu,vuv,waks,eks,yak,zuz,ruddud);$x{$_ x2}=skwer.$x{$_}for a..z;$x{uc$_}=uc$x{$_}for keys%x;%x=reverse%x if$x;$z=join"|",sort{length$b<=>length$a}keys%x;s/\G(.*?)($z)/$1$x{$2}/g;print!$x+0,$_

Test cases:
I have tested successfully the (a),(b),(c) and (d) test cases provided in the OP.
A *somewhat* more readable version:
($x,$_)=split//,<>,2;
@x{a..z,rd}=(e,bub,kut,dud,i,fuf,jug,hash,ay,jag,kak,lul,mum,nun,o,pup,kwak,rut,sus,tut,yu,vuv,waks,eks,yak,zuz,ruddud);
$x{$_ x2}=skwer.$x{$_}for a..z;
$x{uc$_}=uc$x{$_}for keys%x;
%x=reverse%x if$x;
$z=join"|",sort{length$b<=>length$a}keys%x;
s/\G(.*?)($z)/$1$x{$2}/g;
print!$x+0,$_

Nice! Some good test cases to check, it appears I have a lot of work to do!
I've had a quick look at yours and I think you can knock a few bytes off using barewords instead of qw (change qw(bub kut ... yak zuz) to (bub,kut ... yak,zuz)), also you can replace keys%x with @b (since you know what the keys are because of $x). A small change to save another three is $1eq uc($1) to uc$1eq$1. You could also drop the + before the ! of the print for that extra byte to take you to 443.
Hope that's all valid, I've tested limited test cases!

Hmmm, uc$1eq$1 might have to be uc$1 eq$1, but I'm not certain... Sorry if that's wrong!

Thanks Dom for the tips! You saved me 10 chars. Still there's room for improvement, I'll get back to work.. :)

Tcl, 395 394 392
set m { rd ruddud a e h hash o o u yu b bub i ay p pup v vuv c kut j jag q kwak w waks d dud k kak r rut x eks e i l lul s sus y yak f fuf m mum t tut z zuz g jug n nun ঙ skwer}
set m $m[string tou $m]
if [read stdin 1] {puts 0[regsub -all ঙ(.) [string map [lreverse $m] [gets stdin]] {\1\1}]} {puts 1[string map $m [regsub -all (.)\\1 [gets stdin] ঙ\\1]]}

Notes:

Uses skwerruddud for rrd.
skwereskweree for aaaaa.

Example input:
0Hello

Output:
1HASHiskwerlulo

How it works:

m is at the beginning a string.
I concatiate it with the uppercase map.
[string map] does most of the stuff for me (uses a list, so anything that is a valid list...)
regexp for for the double characters. Use a special replacement character (ঙ).

The Bengali Abugida, how did you choose that character?

\ufff iirc. Doesn't really matter. Any non-ascii character would do.

It was \u999. As I said, the only important thing was: not an ascii character.

@JohannesKuhn it fails at example (c), returns 1KWAKWAKSEKS skwerWAKSWAKS RUTskwerrutruddud dudskweriskweriipup.

@psxls Which is correct: A doubled letter is replaced by `skwer` followed by the TUT word for that letter. No mention of SKWER.

Perl 385
$t=e0bub0kut0dud0i0fuf0jug0hash0ay0jag0kak0lul0mum0nun0o0pup0kwak0rut0sus0tut0yu0vuv0waks0eks0yak0zuz;@t=split 0,$t."0\U$t";@s=(a..z,A..Z);while(<>){($-,$_)=split/ /,$_,2;@l{$-?@t:@s}=$-?@s:@t;if($-){for$@(@t){s/skwer$@/$@$@/gi}for$@(@t){s/$@/$l{$@}/g}s/(r)ud/$1/gi}else{s/(.)/$l{$1}||$1/ge;for$@(@t){$r=lc$@eq$@?"skwer":"SKWER";s/$@$@/$r$@/g}s/(ru)t(d)/$1$2$2/gi}$-=!$-;print"$- $_"}

Syntax highlighter hates this one...
Expects input on STDIN, format is 0 (or 1) String to convert here.:
0 Hello! # input
1 HASHiskwerlulo! # output

1 HASHiskwerlulo!
0 Hello!

0 Look for the birds.
1 LULskwerokak fuforut tuthashi bubayruddudsus.

1 LULskwerokak fuforut tuthashi bubayruddudsus.
0 Look for the birds.

0 "Mrs. Hogwallop up and R-U-N-N-O-F-T."
1 "MUMrutsus. HASHojugwaksaskwerlulopup yupup anundud RUT-YU-NUN-NUN-O-FUF-TUT."

1 "MUMrutsus. HASHojugwaksaskwerlulopup yupup anundud RUT-YU-NUN-NUN-O-FUF-TUT."
0 "Mrs. Hogwallop up and R-U-N-N-O-F-T."

Edit: I've noticed an issue with the translation of X (it becomes 'aks' in the reversion, I'll look into this later. Might need to re-order the hash :(.

apart of X, it fails also in OP's examples (b), (c) and check also in my answer the test cases (e) & (g).

This is very true, back to the drawing board!

APL (Dyalog) (372)
You can really tell APL doesn't have built-in string handling functions (except for the generic array ones). I had to write my own tolower (it's L). As always with multiline Dyalog APL, to test it, paste it in an edit window and then call it (T).
T
Q←⎕UCS
L←{Q(Q⍵)+32×⍵∊⎕A}
Z←{⎕←⊃z,.⍺⍺1⌽z←⍵,' '}
w←L¨W←1↓¨W⊂⍨' '=W←' E BUB KUT DUD I FUF JUG HASH AY JAG KAK LUL MUM NUN O PUP KWAK RUT SUS TUT YU VUV WAKS EKS YAK ZUZ RUD SKWER'
⍞{⎕←~⍵:{U←L⍣(l←⍺∊L⎕A)
~l∨⍺∊⎕A:⍺
⍺=⍵:U⊃⌽W
'rd'≡L¨⍺⍵:U'RUD'
U⊃W[96-⍨Q+L⍺]}Z⍺
{'rR'∊⍨v←⊃⍺:v
(⊃⌽w)≡m←L⍺:⍵∇⍬
~w∊⍨⊂m:⍺
L⍣(⍺≡L⍺)⍨⎕A/⍨26↑≡∘m¨w}Z{~×⍴⍵:''
∨/H←⊃¨⍷∘(L⍵)¨w:(⊂l↑⍵),∇⍵↓⍨l←⍴⊃H/W
(⊂⊃⍵),∇1↓⍵}⍺}⎕

Usage:
      T
⎕:
0
"Mrs. Hogwallop up and R-U-N-N-O-F-T."
1
"MUMrutsus. HASHojugwakseskwerlulopup yupup enundud RUT-YU-NUN-NUN-O-FUF-TUT."
      T
⎕:
1
"MUMrutsus. HASHojugwakseskwerlulopup yupup enundud RUT-YU-NUN-NUN-O-FUF-TUT."
0
"Mrs. Hogwallop up and R-U-N-N-O-F-T."

GNU Sed, 514
s/$/\n@a!e@b!bub@c!kut@d!dud@e!i@f!fuf@g!jug@h!hash@i!ay@k!kak@l!lul@m!mum@n!nun@o!o@p!pup@q!kwak@r!rud@r!rut@s!sus@t!tut@u!yu@v!vuv@w!waks@x!eks@y!yak@z!zuz/
s/.*\n\(.*\)/&\U\1@/
ta
:a
s/^1/0\v/
td
s/^0/1\v/
:t
/\v\n/bf
s/\v\([^a-z]\)/\1\v/i
tt
s/\v\([a-z]\)\1/skwer\v\1/
s/\v\([A-Z]\)\1/SKWER\v\1/
s/\v\(.*\)\(.*\n.*@\1!\(\w\+\)@\)/\3\v\2/
s/rut\vd/rud\vd/
s/RUT\vD/RUD\vD/
bt
:d
/\v\n/bf
s/\v\([^a-z]\)/\1\v/i
td
s/\v\(skwer\)/\1\v/i
s/\v\(.*\)\(.*\n.*@\(.\)!\1@\)/\3\v\2/
s/skwer\(.\)\v/\1\1\v/
bd
:f
s/\v.*//

Could probably be shortened, though I'm done for now.
Uses a lookup table to handle conversions in both directions, should handle all exceptions including skwer case and ruddud/RUDDUD correctly.
input taken on each line as 0/1 followed by the string. Uses \v (vertical tab) as a cursor.


text:
Finding nCr for code-golf
The problem is to compute nCr = n!/(r!) * (n-r)! in the fewest characters possible. The input will be in the form: 1st line will have number of test cases and second line will have n and r for each testcase. You need to print ncr
e.g.
Input
1
100 10

Output:
17310309456440

Here's what I have in python. Is there a way to reduce the number of characters further ?[143 chars presently]
r=raw_input
f=lambda x:0**x or x*f(x-1)
C=lambda n,r:f(n)/f(r)/f(n-r)
for i in range(int(r())):print C(*map(int, r().split()))

Thanks!

from sympy import binomial

Python 3 (100 chars)
I=input
C=lambda n,r:r and C(n-1,r-1)*n//r or 1
for _ in' '*int(I()):print(C(*map(int,I().split())))


text:
Test if given number is a Reverse Keith?
Slighty inspired by my previous challenge regarding Keith Numbers I want to propose a challenge to create a function that takes an integer and gives back a true or false depending on the number is a Reverse Keith number or not.
A reverse Keith uses the same little algorithm as Keith numbers, but ends up with it's starting number in reverse.
For example 12 is a Reverse Keith number

12
1 + 2 = 3
2 + 3 = 5
3 + 5 = 8
5 + 8 = 13
8 + 13 = 21

Can a number ending in zero be a reverse Keith number?

Iszi I don't think so.

Bah. That's going to force a little bloat in the code.

For those needing test cases: http://oeis.org/A097060

I've got a couple of questions after looking at some older questions on this site: 1) I noticed that some solutions use command switches. Are these allowed and if so do they count against the length of the solution? The way codegolf.com worked, if I wanted to add the loop switch -n to a Perl script, I'd have to add #!perl -n to the first line, and thus adding 10 characters to the length of the solution. 2) When this assignment (and others) ask for a true/false value, is a 1/0 output acceptable for languages which don't use explicit true/false for boolean values?

APL (28)
⍙∊{1↓⍵,+/⍵}⍣{⊃⍺≥⍙∘←⍎⌽∆}⍎¨∆←⍞

Using more or less the same method as TwiNight did in the other question but reversing the number.
Explanation:

∆←⍞: read a line as text, store in ∆
⍎¨: evaluate each character
{1↓⍵,+/⍵}: add the sum of the list to the end of the list, and drop the first item,
⍣: until
{⊃⍺≥⍙∘←⍎⌽∆}: the first item on the list is greater or equal to ⍙, which is the evaluation (⍎) of the reverse (⌽) of ∆.
⍙∊: see if ⍙ is contained in the final list.

I always wonder how people can write APL.

@moose: you need a special keyboard layout

Not only the symbols ... you also have to know what the symbols mean. I can't even see control structures / loops / IO / variable declaration in that code.

@moose: It's not really hard. There's only about 80 symbols. They are visually distinct, most have at least a semi-obvious visual meaning, and even the ones that don't are internally consistent. For example, if you know that ⍎ is eval, it's not hard to remember that ⍕ is format. I find it a lot easier to read and write than Golfscript.

You used non-ascii even for variable names!!!(;°Д°)

Perl, 126 111 110 chars
$r=reverse$_=shift;$l=@n=split//;while(1){$t=0;$t+=$_ for@n[-$l..-1];push@n,$t;die"true\n"if$r==$t;last if$t>$r}die"false\n";

Should be some room for improvement.
Updated with tips from Dom Hastings:
$r=reverse$_=shift;$l=@n=/./g;push(@n,$t=eval join'+',@n[-$l..-1])&&$r==$t&&die"true\n"while$r>$t;die"false\n"

You forgot that $t isn't being assigned a value with your suggestion, so that adds 3 characters if I want to use that in the following comparisons (it's still cheaper than using $n[-1] twice). However, I can save those by changing split// to /./g.
Slight improvement:
$r=reverse$_=shift;$l=@n=/./g;push@n,$t=eval join'+',@n[-$l..-1]and$r==$t&&die"true\n"while$r>$t;die"false\n"

Replaced && operators with lower precedence and to be able to drop parentheses around call to push. Saves one character.

Hi Flesk, thought I'd contribute a few extra savers:
changing:
$t=0;$t+=$_ for@n[-$l..-1];push@n,$t
to:
push@n,eval join'+',@n[-$l..-1]
saves a few bytes and changing:
die"true\n"if$r==$t
to:
$r==$t&&die"true\n"
-0 char change, but now can use another statement modifier, changing:
while(1){...last if$t>$r}
to:
...while$r>=@n[-1]
all those (and dropping the last semi-colon) should save you 15 chars in total!

Thanks for the tips. I'll definitely reuse eval join'+' in the future.

@DomHastings: I updated my answer with your suggestions.

Ah, nice catch with split// to s/./g, glad to have helped!

Mathematica 157 96
f = (d = IntegerDigits@#; r = FromDigits@Reverse@d;
NestWhile[Rest@Append[#, Tr@#] &, d, Max@# < r &][[-1]] == r) &

Based on code by Anton Vrba and considerably streamlined by @ssch.
f[11]
f[12]
f[20]
f[24]

False
True
False
True

Something's wrong here. The numbers you have appear to be a series of Keith Numbers - not Reverse Keith Numbers. From Wikipedia's article on Keith Numbers, under Examples: 14, 19, 28, 47, 61, 75, 197, 742, 1104, 1537, 2208, 2580, 3684, 4788, 7385, 7647, 7909.... I don't know certainly about the rest, but I tested 14 and it definitely is not a Reverse Keith Number. Its progression jumps from 37 to 60, where it would need to pass through 41 to be a Reverse Keith Number. 1+4=5, 4+5=9, 5+9=14, 9+14=23, 14+23=37, 23+37=60

Fair enough.  I grabbed the wrong code.

A real hint should have been when the "find all" bit didn't produce the example given in the question, 12. ;-)

I rolled back to an earlier, correct version.

You can drop it down to 93  (   d = IntegerDigits[#];   r = FromDigits@Reverse@d;   NestWhile[Rest@Append[#, Tr@#] &, d, Max@# < r &][[-1]] == r   ) &

PowerShell: 149 135
Mostly derived from my original Keith Number Checker. I'm sure there's still some work to be done.
$k=+(($j=($i=+(read-host))-split''|?{$_})[99..0]-join'');While($x-lt$k){$x=0;$j|%{$x+=$_};$null,$j=$j+$x}$x-eq$k-and$i-gt9-and$i%10-ne0

I definitely need to double-check for redundant parenthesis and semicolons. It's possible one of the casts to integer is unnecessary. One thing I might also need to spend time on is finding out if I can avoid false-positives without -and$i%10-ne0.
It'd be really nice if there was a reliable way to do a left-shift-and-append that's shorter than $null,$j=$j;$j=@($j);$j+=$x.

EDIT: Found it! $null,$j=$j+$x

Cleanup $x between runs, and also $i, $j, $k when you're done.

Game Maker Language, 129 136
Make this the function/script f and compile with uninitialized variables as 0.
a=argument0;while(a>0){b*=10b+=(a mod 10)b div 10}k[]=1k[1]=1while(k[c]<b){c+=1k[c]=k[c-1]+k[c-2]}while(e<c){e+=1if k[e]==b r=1}return r

It returns true or false; call with f(any number you want)
Edit #1 Corrected invalid operators % and /= with mod and div.

Haskell, 106
This version only works for 0 < x < 100 though.
k x=(last$takeWhile((>=)x)(let f=(map(Data.Char.digitToInt)$reverse$show x)++zipWith(+)f(tail f)in f))==x

TODO: check up on Test if given number if a Keith number and implement a proper algorithm.

So... this only works on the first 6 Reverse Keith numbers? Kinda weak.

yeah, I didn't really have the algorithm down yet when I wrote this, and since it was 3 AM I decided to call it quits.