Shammer's Philosophy

My private adversaria

Bash Shell Script my pocket reference - 20100812

if 文 sample

if [ $# -ne 1 ];then
    echo "Usage: $0 [123]";
    exit 1;
fi

if [ $1 -eq 1 ];then
    echo "You are number#1.";
elif [ $1 -eq 2 ];then
    echo "You are number#2.";
elif [ $1 -eq 3 ];then
    echo "You are number#3.";
else
    echo "Invalid argument.";
    echo "Usage: $0 [123]";
fi

for 文 sample

Shell Script
for i in `seq 1 5`
do
    echo $i
done
One liner
for i in `seq 1 5`;do echo $i;done

外部ファイル読み込み処理

while read line;
do
    // 各行ごとに何らかの処理を実施。
    // 読み込んだ行は line に格納されている。
done < $TARGET_FILE

substring

function substring(){
    if [ $2 -lt 1 ];then
	echo "Usage: 2nd argument should be bigger than 1.";
	exit 1;
    elif [ $2 -gt $3 ];then
	echo "Usage: 3rd argument should be bigger than 2nd argument.";
	exit 1;
    elif [ $# -ne 3 ];then
	echo "$0 requires 3 arguments.";
	echo "1st argument is a string.";
	echo "2nd argument is a start point to cut.";
	echo "3rd argument is a last point to cut.";
	exit 1;
    fi
    result=`echo $1 | cut -c $2-$3`
    echo $result
}