Posts Tagged ‘loop’

bash commands

November 12th, 2010

1. for loop

for (( EXP1; EXP2; EXP3 ))
do
	command1
	command2
	command3
done

eg:

#!/bin/bash
for (( i=0; i<5; i++ ))
do
	echo "Hello $i..."
done

2. if / else / fi statements

basic grammar (note the spaces between the [ ]):

if [ EXP ]; then
	statements...
else
	statements 2...
fi

eg:

step=5
alpha=$(echo "scale=1; $step/10" | bc)
if [ $(echo "$alpha<1" | bc) -eq 1 ]; then
	alpha=0$alpha
fi

2.1 Arithmetic Comparisons

-lt <
-gt >
-le <=
-ge >=
-eq ==
-ne !=

2.2 String Comparisons

= equal
!= not equal
< less then
> greater then
-n s1 string s1 is not empty
-z s1 string s1 is empty

3. real number calculation

(echo "scale=2; EXP" | bc)

where scale=2 sets the number of the digits after decimal point.
eg1:

a=1;b=2;
c=$(echo "scale=2; $a/$b" | bc)
echo $c

output:

.50

eg2:

exp="1223/234";
d=$(echo "scale=2; ${exp}" | bc)
echo $d

output:

5.22

reference: http://linuxconfig.org/Bash_scripting_Tutorial

4. functions

basic grammar:

function div() {
    STATEMENTS
    return XXX
}>
NOTE: A bash function can only return a number. There is no way to return directly a string. So we need to use $() to capture the result outputted in the function body.
eg:
# ----------------------------------------------
# return $1/$2 with 1 digit after decimal point.
# ----------------------------------------------
function div() {
   res=$(echo "scale=1; $1/$2" | bc)
   if [ $(echo "$res<1" | bc) -eq 1 ]; then
      res=0$res
   fi
   echo $res
}
# use the function
step=5
alpha=$(div $step 10)

loop through json object

July 2nd, 2010

p = {k1: v1, k2, v2, k3, v3};
for (var key in p) {
if (p.hasOwnProperty(key)) { // make sure that the key you get is an actual property of an object, and doesn’t come from the prototype:
alert(p[key]);
}
}