工具Learn shell script by sample程序员

shell script 逐行读取配置文件

2016-04-24  本文已影响823人  lvjian700

本文将介绍一种方法用来逐行读取如下配置文件,其中将使用 readIFS 指令。

配置文件:

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

通常情况下 readIFS 会一起配合使用。其中

使用 read 读取一行数据到变量:

文件:

sqs:aws-sqs-queue-name

shell script

file=$1
read -r line <<< "$file"
echo $line # => sqs:aws-sqs-queue-name

此时 -r 参数代表 raw,忽略转移字符。例如将 \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

实战应用

最近在处理 AWS SNS(Simple Notification Service)SQS(Simple Queue Service) 时,由于 AWS SNS 的限制,不能使用 Cloudformation Stack 修改 SNS Topic 的 Subscriptions,只能通过 AWS Console 或者 aws-cli 更新 subscriptions。

因此采用了如下方案:

  1. 使用 Cloudformation stack 管理 SNS 和 SQS
  2. 使用 aws-cli 管理 subscriptions (写 shell script)

使用 shell 逐行读取文件出现在步骤2中。

为了方便管理,所有 Subscriptions 放在配置文件中:

配置文件:

sqs:aws-sqs-queue-name
email:myemail@gmail.com

shell script 会解析上述文件,并且执行两条 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"

参考资料

上一篇下一篇

猜你喜欢

热点阅读