Shammer's Philosophy

My private adversaria

Bash Shell Script my pocket reference - 20150217

Bash Shell Script my pocket reference - 20150213 - Shammerismの内容にBash 終了判定 - Shammerismの内容を追記。こんな記事書いていたんだと思った。。。

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

if [ ! -e $HOME/bin ];then
    echo "$HOME/bin is not exists";
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
}

Equal判定

if [ $VALUE = "0" ];then
    echo "VALUE is 0";
else
    echo "VALUE is not 0";
fi

空文字判定

if [ -z $VALUE ];then
    echo "VALUE is blank."
else
    echo "VALUE is $VALUE.";
fi

抜き出し

# echo "0123456789" | cut -c 5-6
45
#

長さ判定

# printf 0123456789 | wc | awk '{print $3}'
10
#

ファイル名一括変換

$ ls -l *JPG | awk '{print $9}' > aaa;while read line;do mv $line "Prefix-$line";done < aaa;rm aaa;
$

終了判定

$?を使用する
if [ $? -eq 0 ];then
  echo "Pre command succeeded!";
else
  echo "Pre command failed.";
fi
function1成功時のみcommand1を実行する
$ function1 && command1
$
function1失敗時のみcommand1を実行する
$ function1 || command1
$

function1がワンライナーでsyntax errorがあったときには、この書き方ではcommand1は実行されなかった。