シェルスクリプト工房を完走したので覚書として
使用した基本事項をまとめてみます。
◆テンプレート
ファイル:hello.sh
-------------------------
#!/bin/bash
echo "Hello World !"
exit 0
-------------------------
・実行方法
sh hello.sh
・実行結果
Hello World !
◆代表的な構文とコマンド
・if文
-------------------------
if [ 条件 ]; then
処理
elif [ 条件 ]; then
処理
else
処理
fi
-------------------------
※条件の指定方法については次のサイトが
非常に参考になったのでよかったら併せて参照ください。
参考:if 文と test コマンド
例)
target="./sample.txt"
if [ ! -d $target ]; then
echo "target is not directory"
else
echo "target is directory"
fi
・for文
-------------------------
for 変数 in 代入する値のリスト
do
処理
done
-------------------------
例)
#!/bin/bash
for i in "$@"
do
echo $i
done
実行結果
$ sh for.sh a.txt b.txt
a.txt
b.txt
・read コマンド
標準入力を受け付ける
例)
read str
echo $str
・ ”.”
設定ファイルを読み込む
例)ローカルに保存されているファイル(.sample.txt)
. "./sample.txt"
◆よくある使い方
シェルスクリプトというよりLinuxでよく用いる形です。
・grepとパイプ(|)
◆特殊なシェル変数
シェルスクリプトでよく用いるシェル変数の一覧です。
(参考:シェルの変数に慣れる)
・$数字
シェルスクリプトやコマンドを実行した際の引数が記録されています。
例) sh hello.sh a.txt b.txt
$1 は a.txt
$2 は b.txt
です。
・$#
シェルスクリプト実行時に与えられた引数の数
例) sh hello.sh a.txt b.txt
$# は 2
です。
・$0
実行されたシェルスクリプトのファイル名を表します。
例) sh hello.sh
$0 は hello.sh
です。
・$@
引数変数をスペースで区切ってすべて表示します。
例) sh hello.sh a.txt b.txt
$@ は a.txt b.txt
です。
最後まで読んでいただきありがとうございます。
随時ブラッシュアップしていく予定なので
記載したほうが良い、記載して欲しい内容などありましたらご指摘くださいm(__)m
