便利コマンド
一括リネーム
rename from to pattern
patternに合致したファイルの、fromに一致する部分をtoに変更
例:
rename .htm .html *.htm
tar
- .gitを除く --eclude
- 指定のディレクトリに移動してから、アーカイブ対象指定パスを解釈 -C
- アーカイブに記録されるパスを書き換え --transform
- --transformで変換後のファイル名を表示 --show-transformed-name
tar -zcvf $TARGZ -C $PROJ_DIR --exclude=./.git --transform='s:^\.:foo:' --show-transformed-name .
ディレクトリだけの一覧
lsコマンドのオプションには該当するものがない模様。
find . -type d
再帰的に辿らず、このディレクトリだけ調べる場合
find . -type d -maxdepth 1
結果に 「.」 が含まれるのを避けたい場合
find . -type d -maxdepth 1 -name "*"
このディレクトリではなく、1個下のディレクトリを調べる
find . -type d -mindepth 2
または
find */. -type d
date
YYYYMMDD
date +%Y%m%d
YYMMDD
date +%y%m%d
シェルスクリプトのデバッグ
文法チェック
/bin/bash -n foo.sh
トレース
/bin/bash -x foo.sh
shシェルスクリプト
リテラル
文字列 "hello $foo" 変数展開あり 'hello $foo' 変数展開なし
変数
foo
変数への代入
foo="hello" foo=hello foo='hello world' foo="hello world" = の前後にスペースを入れてはいけない。
以下は誤り foo=hello world → コマンド実行の文法に該当し( var=val var=val command ... )、コマンドworldが実行される。その際環境変数fooがセットされる。
変数の値の取得
$foo ${foo}
コメント
# this is comment
外部プログラム、シェル内コマンドの実行
command arg1 arg2 arg3 ...
1行1コマンドを書く場合は 行末に ; などの区切り記号は不要。 exit code が変数 $? に代入される。
`command arg1 arg2 arg3 ...` コマンドを実行し、その出力結果に置換される。???
関数定義
myfunction() { arg1=$1 arg2=$2 }
引数は$1, $2, ... で渡される。
関数呼び出し = コマンド実行と同じ
myfunction arg1 arg2 ... argn
list
1個以上のpipelineで、;, &, &&, || で区切られたもの。 最後に;, &, 改行を付けることもできる。
制御文
if list; then list; else list; fi
if コマンドc then コマンドt1 コマンドt2 ... else コマンドf1 コマンドf2 ... fi
while文 while コマンド do コマンド done
case文 case 文字列 in パターン,...) コマンド コマンド ;; *) コマンド コマンド ;; esac
testコマンド
test 式 または [ 式 ]
式を評価し、trueなら0を、falseなら1をexit statusとして返す。
文字列 文字列が空文字列でなければtrue -z 文字列 文字列が空文字列ならtrue 文字列 = 文字列 文字列が等しければtrue 文字列 != 文字列 文字列が等しくなければtrue
整数 -eq 整数 整数 -ne 整数
論理演算 ! 式 not 式 -o 式 or 式 -a 式 and (式) 式がtrueならtrue
-o より -a のほうが優先度が高い
詳しくは、 man test
###
コマンドライン引数
$1 $2 ...
$nを$n-1に移動
shift
ssh server command arg1 arg2 ....
foo > somefile というのをserverで実行させたければ
ssh server 'foo > somefile'
または
ssh server foo '<' somefile
です。
ヒアドキュメント
http://www.geocities.jp/geo_sunisland/input_output.html
cat <<EOT >foo.log aaa bbb ${VAR} EOT
文字列演算子
http://www.hpc.cs.ehime-u.ac.jp/~aman/linux/bash/shell_prog1.html#4.3_string_operator
終了ステータス
$?
0で正常。0以外はエラー
if [ $? -eq 0 ]; then 正常の場合 fi
- 成功した場合のみ次のコマンドを実行
command1 && command2
- 失敗した場合のみ次のコマンドを実行
command1 || command2
for
http://www.koikikukan.com/archives/2014/03/03-015555.php
for foo in aaa bbb ccc do 繰り返す内容 done
fooに文字列aaa, bbb, ccc が順に代入され、実行される。
for foo in {3..9}
fooに3,4,5...9が順に代入される。
for foo in $(コマンド)
コマンドの実行結果(標準出力への出力内容?)の各行が順に代入される。