Linux tip
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
list directories
find -type d -maxdepth 1
Shell script
特殊な変数
変数 |
説明 |
$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
copy a file to multiple directories
#!/bin/bash
for DIR in $(ls -d hoge_*)
do
echo $DIR
cp ./hoge1.dat ./$DIR/hoge.dat
done
Loop with counts
#!/bin/bash
i=0
while [ $i -lt 5 ]; do
echo $i
i=`expr $i + 1`
done
引数すべてに同じ処理をする
#!/bin/sh
echo hi $*
for name in $*
do
echo hi $name
done
if 文
word=2
if [ $word -eq 1 ]; then
echo "if"
elif [ $word -eq 2 ]; then
echo "elif"
else
echo "else"
fi
ディレクトリの存在チェック
if [ ! -d "$DIR" ]; then
echo "$DIR" " is not a directory"
exit 1
fi
* -e ファイルが存在する(ディレクトリを含むどのようなタイプのファイルであっても)。
* -f レギュラーファイル(ディレクトリ等を除く)が存在する。
* -d ディレクトリが存在する。
* -r ファイルが存在し、リード権がある。
* -s ファイルが存在し、フィルサイズが0でない。
直前のコマンドの終了ステータスで終了する
exit $?
Lock ファイルの利用
#!/bin/sh
LOCKFILE=/tmp/.lock
if [ -e $LOCKFILE ]
then
echo "Already Running"
else
touch $LOCKFILE
echo "OK"
sleep 10
rm $LOCKFILE
fi
Vi
Change color
hi Comment ctermfg=DarkBlue guifg=Blue
hi Statement ctermfg=DarkRed guifg=Brown
hi Identifier ctermfg=Blue guifg=DarkCyan
hi PreProc ctermfg=Magenta guifg=Purple
hi Constant ctermfg=Black guifg=Magenta
hi Special ctermfg=DarkMagenta guifg=SlateBlue
hi Type ctermfg=DarkCyan guifg=SeaGreen
hi Ignore ctermfg=Gray guifg=bg
:let &background = ( &background == "dark"? "light" : "dark" )
最終更新:2008年09月17日 17:01