Posted: 2021-08-03
| Categories:
bash
| Tags:
bash ,
引数
テンプレート、get_blocklist()関数、get_mac_addresslist()関数、ヘルプを表示する usage_exit()関数は用意してあるものとする
if [ $# -eq 0 ]; then
get_blocklist
exit
fi
while getopts "bmh" OPT
do
case $OPT in
b) get_blocklist
hoge="hogehoge"
;;
m) get_mac_addresslist
;;
h) usage_exit
;;
\?) usage_exit
;;
esac
done
shift $((OPTIND - 1))
最後の shift $((OPTIND - 1)) だが、これはコマンドライン中のオプションの部分を削除する動作
注意点 getopts コマンドでオプションを使ったシェルプログラミングは楽しい ♪
source などで呼ぶと変数領域がそのまま引き継がれる様子。
個人的には bash だと全部グローバル変数なので、変数は汚染されやすいよな、と思う
Read more... Posted: 2021-07-30
| Categories:
bash
| Tags:
bash ,
引数
cat file | while read ... より while read ...; do ...; done < <(...) の方が、ループ本体を現在のシェルで実行できるので変数を保持しやすい。IFS='=' read -r key value <<<"$pair" の形で key=value を分解できる。動的な変数代入が必要でも eval は避け、local "$key=$value" のように扱う方が安全。 create_tags() {
local instance_id=$1
shift
local tags=""
local pair key value
for pair in "$@"; do
IFS='=' read -r key value <<<"$pair"
if [[ -z "$key" || -z "$value" ]]; then
echo "$0 ${FUNCNAME[0]}: 第2引数以降は key=value の形式で指定してください" >&2
echo " 受け取った値: ${key}=${value}" >&2
exit 4
fi
local "$key=$value"
tags="$tags Key=$key,Value=$value"
done
tags="$tags Key=Creator,Value=${USER}@${HOSTNAME}"
echo "$tags"
# aws ec2 create-tags --tags $tags --resources "$instance_id"
}
create_tags i-02d848a7 Name=inoue-test1 Nodes=default ROLES=ekitan_essence hogehoge=4
Read more...