Stupid Tricks: bash
November 12, 2012This 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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
for i in {1..100}; do | |
echo -ne "\r$i" | |
sleep .5 | |
done | |
echo |
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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function hello-world { | |
local __resultvar=$1 | |
local __blah="Hello, world!" | |
eval $__resultvar="'$__blah'" | |
} | |
hello-world foo | |
echo $foo |
You can scale this to return as many values as you want from a function.
I use this one all the time.
Concatenate strings:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
a="hello" | |
b="world" | |
c=$a" there, isn't it a wonderful "$b"?" | |
echo $c |
It really is as simple as mushing them together like that.
That's all for now. Thanks, for reading!