2011年8月25日 星期四

shell script (constructs)


if...else...fi

num1=1
num11="1"


num2=2
num22="2"


#if...else...fi
echo "if...else...fi"
echo
    #value
    if [ $num1 -eq $num11 ]; then
        echo "int equal"
    else
        echo "int not equal"
    fi
    echo


    #string
    if [ ${num11} == ${num22}  ];  then
        echo "str equal"
    else
        echo "str not equal"
    fi
    echo
<span class="fullpost">
for...done



#for...done
echo "for...done"
echo
    #string
    for animal in dog cat elephant
    do
        echo "there are ${animal}s";
    done
    echo


    #value
    for val in 1 2 3
    do
        echo `expr 2 \* $val`
    done


    #value2
    s=0
    for (( i=1; i<=2; i=i+1 ))
    do
        s=$(($s+$i))
    done
    echo "The result of '1+2+3+...+$nu' is ==> $s"
while...do....done



#while...do...done
echo "while...do...done"
wh_val=5
while [ $wh_val -ne 0 ];
do
    echo "$wh_val"
    wh_val=`expr $wh_val - 1`
done
case...esac

#case ..... esac
ary_fruit=("Apple" "Banana" "Guava")
for loc in 0 1 2
do
    case ${ary_fruit[$loc]} in
        "Apple")
            echo this fruit is ${ary_fruit[$loc]}
            ;;
        "Banana")
            echo this fruit is ${ary_fruit[$loc]}
            ;;
        "Guava")
            echo this fruit is ${ary_fruit[$loc]}
            ;;
    esac
done



result

steven@ATM64:~/base_shell$ sh constructs.sh
if...else...fi


int equal


str not equal


for...done


there are dogs
there are cats
there are elephants


2
4
6
The result of '1+2+3+...+' is ==> 3
while...do...done
5
4
3
2
1


this fruit is Apple
this fruit is Banana
this fruit is Guava


</span>

沒有留言:

張貼留言