「Batch script/DOS」の編集履歴(バックアップ)一覧はこちら
「Batch script/DOS」(2008/08/26 (火) 05:55:31) の最新版変更点
追加された行は緑色になります。
削除された行は赤色になります。
#contents
* Shell script
** Give permisson to script
chmod u+x hoge.sh
** Redirect to files
./sysbackup.sh > log.txt 2> err.txt
./sysbackup.sh > log.txt 2>&1
** 特殊な変数
|変数| 説明|
|$n| nは数字であり、$0はシェルスクリプト名、以降$1、$2…は第1引数、第2引数…である。第10引数以降は${10}、${11}…で参照する。|
|$# |与えられた引数の個数|
|$@ |$0以外の全ての引数("$@"のようにダブルクォーテーションで囲んだ場合"$1" "$2" …"のように個別に展開される。)|
|$* |$0以外の全ての引数("$@"のようにダブルクォーテーションで囲んだ場合"$1 $2 …"のように展開される。)|
|$? |最後に実行したコマンドの終了ステータス|
|$! |最後に実行したバックグラウンドコマンドのPID|
|$$ |シェルのPID|
|$- |現在のオプションフラグ|
** コマンドの実行結果を利用する
コマンドの実行結果を変数に代入したいときは、そのコマンドを`(バッククオート)で囲みその結果を変数に入れます。
** 変数を数値として扱いたい
declare -i test
test=1
test=$test+1
echo $test
** 変数に対するパターンマッチ
$ echo ${testpath##/*/}
how.to.linux
$ echo ${testpath#/*/}
sekino/Linux/how.to.linux
$ echo ${testpath%%.*}
/home/sekino/Linux/how
$ echo ${testpath%.*}
/home/sekino/Linux/how.to
** list directories
find -type d -maxdepth 1
** copy a file to multiple directories
#highlight(shell){{
#!/bin/bash
for DIR in $(ls -d hoge_*)
do
echo $DIR
cp ./hoge1.dat ./$DIR/hoge.dat
done
}}
** Loop with counts
#highlight(shell){{
#!/bin/bash
i=0
while [ $i -lt 5 ]; do
echo $i
i=`expr $i + 1`
done
}}
** 引数すべてに同じ処理をする
#highlight(shell){{
#!/bin/sh
echo hi $*
for name in $*
do
echo hi $name
done
}}
** if 文
#highlight(shell){{
word=2
if [ $word -eq 1 ]; then
echo "if"
elif [ $word -eq 2 ]; then
echo "elif"
else
echo "else"
fi
}}
** ディレクトリの存在チェック
#highlight(shell){{
if [ ! -d "$DIR" ]; then
echo "$DIR" " is not a directory"
exit 1
fi
}}
* -e ファイルが存在する(ディレクトリを含むどのようなタイプのファイルであっても)。
* -f レギュラーファイル(ディレクトリ等を除く)が存在する。
* -d ディレクトリが存在する。
* -r ファイルが存在し、リード権がある。
* -s ファイルが存在し、フィルサイズが0でない。
** 直前のコマンドの終了ステータスで終了する
exit $?
** Lock ファイルの利用
#highlight(shell){{
#!/bin/sh
LOCKFILE=/tmp/.lock
if [ -e $LOCKFILE ]
then
echo "Already Running"
else
touch $LOCKFILE
echo "OK"
sleep 10
rm $LOCKFILE
fi
}}
* Batch script
#contents
* Batch script