shell script 逐行讀取配置文件

本文將介紹一種方法用來逐行讀取如下配置文件,其中將使用 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 通常用于讀取數(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。

因此采用了如下方案:

  1. 使用 Cloudformation stack 管理 SNS 和 SQS
  2. 使用 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"

參考資料

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容

  • 為何叫做 shell ? shell prompt(PS1) 與 Carriage Return(CR) 的關系?...
    Zero___閱讀 3,185評論 3 49
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,915評論 18 139
  • 在 Linux 或類 UNIX 系統(tǒng)下如何使用 KSH 或 BASH shell 逐行讀取一個文件? 在 Linu...
    Hackart閱讀 1,208評論 0 3
  • 1.創(chuàng)建文件夾 !/bin/sh mkdir -m 777 "%%1" 2.創(chuàng)建文件 !/bin/sh touch...
    BigJeffWang閱讀 10,186評論 3 53
  • Ubuntu的發(fā)音 Ubuntu,源于非洲祖魯人和科薩人的語言,發(fā)作 oo-boon-too 的音。了解發(fā)音是有意...
    螢火蟲de夢閱讀 99,553評論 9 467