シェルスクリプトの書き方
基本
一行目の
#!/bin/sh シェルスクリプトの宣言
スクリプトファイルを作ったら属性変更を行う
$ chmod +x hogehoge.sh
実行の際は
$ ./hogehoge.sh
コメントは
#
ワイルドカード
* 文字全部
? 1文字
[...] []に含まれる文字どれか1つ
[!...] []に含まれない文字
例
[a-zA-Z]
[!0-9]
バッククォートによる置換
例
$ echo "Today is `date`"
$ STRING=`echo "abc"`
コマンド終了時のステータス
if test -f file
then
echi "file exists"
fi
成功が0、失敗が0以外
コマンドセパレータ
改行 1つのコマンド区切り
; 1つのコマンド区切り
| パイプ
& バックグランド実行
|| OR演算子 (前のコマンドが失敗した場合のみ実行)
&& AND演算子 (前のコマンドが成功した場合のみ実行)
制御文
if
if command-list
then
command
else
command
fi
例
if test -f file
then
echo "file exists"
else
echo "file does not exist"
fi
testコマンドは[]で代用可能
if [-f file]
複数条件は
elif
for
for variavle in word-list
do
command
done
例
for i in a b c d
do
echo $i
done
while
while command-list
do
command
done
例
a=1
while test $a -lt 3 #aが3より小さいか
do
echo $a
a=`wxpr $a +1`
done
割り込み
while :
do
.....
if .....
then
break
fi
done
case
case string in
pattern1) commandlist ;;
pattern2) commandlist ;;
pattern3) commandlist ;;
esac
一致した時点でコマンドを実行し、その後の一致する条件があったとしても無視する。
test
ある条件を判定し、正しい場合には0を返す