Category Archives: bash

Sorting a loop in bash and other possibilites

As I said in my previous post, I learned a couple things about bash today. I had a nice for loop that outputted the info I wanted, but not in the right order. I thought to myself, man if this were php I would just put it in an array and sort it before looping across it. I bet this will be a pain in bash.

BUT, I was pleasantly surprised to find out how simple this really was. If you want to perform an action the output of a loop in bash then you just pipe done into the fuction you want performed. See the example below.

for VAR in $VARS; do
done | sort -n

Cool, right?

Lineing up fields with BASH (or other programming languages)

Learned a couple things about bash today. I was wanting to print something out nicely, so I was using tabs to separate fields. As you know, nothing ever lines up if you do not have values very similar in size. So I was about to search Google for the problem when I had a moment of sheer brilliance. 🙂 I thought I’ll just concatenate a bunch of spaces on the end of the variable and then use cut to grab how many characters I want. I was very proud of myself, but then bash quickly humbled me by condensing all my spaces I had added to the variable.

So, back to the all knowing Google. Turns out you have to quote your variable when you use it if you don’t want bash to truncate the spaces. So I quoted my variable when using it and all is good.

BUFFER="$VAR                                                                "
NICE_VAR=`echo "$VAR" | cut -c -15`
echo "$VAR $VAR2"