a→ab

computation, game design, and experimentation


front page | about | archives | code dump | c.s. for mere mortals | tags | rss feed

Stupid Tricks: bash

November 12, 2012
tags:  bashstupid trickshackscode-dump

This article showcases a few stupid bash tricks that I've gathered in my recent employment as a unix sysadmin. Some of these aren't all that useful, but they are neat.

First up, a fun toy:

for i in {1..100}; do
echo -ne "\r$i"
sleep .5
done
echo
view raw slash-r.sh hosted with ❤ by GitHub

Running this, you'll see a counter that rises from 1 to 100, overwriting itself as it goes. You could use this with some trickery to give a visual indicator of how far done a process is, for example.

Next up, returning a value from a function:

function hello-world {
local __resultvar=$1
local __blah="Hello, world!"
eval $__resultvar="'$__blah'"
}
hello-world foo
echo $foo
view raw return-value.sh hosted with ❤ by GitHub

You can scale this to return as many values as you want from a function.
I use this one all the time.

Concatenate strings:

a="hello"
b="world"
c=$a" there, isn't it a wonderful "$b"?"
echo $c
view raw concat.sh hosted with ❤ by GitHub

It really is as simple as mushing them together like that.

That's all for now. Thanks, for reading!