本文將介紹一種方法用來逐行讀取如下配置文件,其中將使用 read
和 IFS
指令。
配置文件:
sqs:aws-sqs-queue-name
email:myemail@gmail.com
shell script
while IFS='' read -r line || [[ -n "$line" ]]; do
IFS=':' read -r protocol endpoint <<< "$line"
echo "Protocol: $protocol - Endpoint: $endpoint"
done < "$file"
輸出:
Protocol: sqs - Endpoint: aws-sqs-queue-name
Protocol: email - Endpoint: myemail@gmail.com
read 和 IFS
通常情況下 read
和 IFS
會一起配合使用。其中
-
read
通常用于讀取數(shù)據(jù)和用戶輸入,文本使用它從字符串中讀取變量。 -
IFS(Internal Field Separator)
用來 read 指令中的分隔符。我們可以用分割字符串,并且讀取到不同的變量中。
使用 read 讀取一行數(shù)據(jù)到變量:
文件:
sqs:aws-sqs-queue-name
shell script
file=$1
read -r line <<< "$file"
echo $line # => sqs:aws-sqs-queue-name
此時 -r
參數(shù)代表 raw
,忽略轉(zhuǎn)移字符。例如將 \n
視為字符串,而不是換行符。
讀取用戶名和hostname:
echo "ubuntu@192.168.1.1" | IFS='@' read -r username hostname
echo "User: $username, Host: $hostname" # => User: ubuntu, Host: 192.168.1.1
讀取程序的版本號:
git describe --abbrev=0 --tags #=> my-app-1.0.1
$(git describe --abbrev=0 --tags) | IFS='-' read -r _ _ version
echo $version # => 1.0.1
實戰(zhàn)應用
最近在處理 AWS SNS(Simple Notification Service) 和 SQS(Simple Queue Service) 時,由于 AWS SNS 的限制,不能使用 Cloudformation Stack 修改 SNS Topic 的 Subscriptions,只能通過 AWS Console 或者 aws-cli 更新 subscriptions。
因此采用了如下方案:
- 使用 Cloudformation stack 管理 SNS 和 SQS
- 使用 aws-cli 管理 subscriptions (寫 shell script)
使用 shell 逐行讀取文件
出現(xiàn)在步驟2
中。
為了方便管理,所有 Subscriptions 放在配置文件中:
配置文件:
sqs:aws-sqs-queue-name
email:myemail@gmail.com
shell script 會解析上述文件,并且執(zhí)行兩條 aws-cli 指令
file=@1
while IFS='' read -r line || [[ -n "$line" ]]; do
IFS=':' read -r protocol endpoint <<< "$line"
# create subscription for the topic
aws sns subscribe --topic-arn $topic_arn --protocol $protocol --notification-endpoint $endpoint
done < "$file"