Shammer's Philosophy

My private adversaria

Bash Shell Script my pocket reference - 20151206

Updated from Bash Shell Script my pocket reference - 20150923 - Shammerism. Added the way how to use array on bash.

if 文 sample

if basic
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
The file exists
if [ -e $HOME/bin ];then
    echo "$HOME/bin exists";
fi
The file does NOT exist
if [ ! -e $HOME/bin ];then
    echo "$HOME/bin does not exist";
fi
AND is -a
if [ $X = "a" -a $Y = "b" ];then
  echo "OK"
fi
OR is -o
$ echo $X
a
$ echo $Z

$ if [ -z "$X" -o -z "$Z" ];then echo "OK";fi
OK
$

for 文 sample

Shell Script
for i in `seq 1 5`
do
    echo $i
done
for with array

Array can be defined with blank. Then using [@] can access all elements. If without [@], only first element can be accessed.

array=("AAA" "BBB" "CCC" "DDD");
for element in ${array[@]};
do
    echo $element;
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
大文字と小文字を無視する(事前に全部大文字にしてしまう)
VALUE=`echo $1 | tr '[a-z]' '[A-Z]'`;
if [ $VALUE = "A" ];then
    echo "VALUE is a or A";
else
    echo "VALUE is not a or A";
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は実行されなかった。