Suppose you have 11 marbles, 4 of which are red, the rest being blue. The marbles are indistinguishable, apart from colour. How many different ways are there to arrange the marbles in a line? And how many ways are there to arrange them so that no two red marbles are adjacent?

There are simple mathematical solutions to these questions, but it's also possible to generate and count all possibilities directly on the command line, using little more than brace expansion, grep and wc!

The answer to the question posed above is that there are 330 ways of arranging the marbles in a line, 70 of which have no two red marbles adjacent. See the sample output.

To follow the call to marbles 11 4: after c=''; for i in $(seq $1); do c+='{b,r}'; done;, $c equals {b,r}{b,r}{b,r}{b,r}{b,r}{b,r}{b,r}{b,r}{b,r}{b,r}{b,r}

After x=$(eval echo $c), and brace expansion, $x equals bbbbbbbbbbb bbbbbbbbbbr ... rrrrrrrrrrb rrrrrrrrrrr, which is all 2^11 = 2048 strings of 11 b's and r's.

After p=''; for i in $(seq $2); do p+='b*r'; done;, $p equals b*rb*rb*rb*r

Next, after y=$(grep -wo "${p}b*"

Finally, grep -vc 'rr'

by David Winterbottom (codeinthehole.com)

]]>If the return code from the last command was greater than zero, colour part of your prompt red. The commands give a prompt like this:

[user current_directory]$

After an error, the "[user" part is automatically coloured red.

Tested using bash on xterm and terminal. Place in your .bashrc or .bash_profile.

by David Winterbottom (codeinthehole.com)

]]>tail -c 1 "$1" returns the last byte in the file.

Command substitution deletes any trailing newlines, so if the file ended in a newline $(tail -c 1 "$1") is now empty, and the -z test succeeds.

However, $a will also be empty for an empty file, so we add -s "$1" to check that the file has a size greater than zero.

Finally, -f "$1" checks that the file is a regular file -- not a directory or a socket, etc.

by David Winterbottom (codeinthehole.com)

]]>by David Winterbottom (codeinthehole.com)

]]>