日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

shell腳本如何讀取properties文件中的值_linux shell

作者:巴山農夫 ? 更新時間: 2022-05-14 編程語言

如下面代碼所示的properties文件是各種編程語言中常用的屬性文件,通過key讀取value是極其常見的需求。

# 端口
server.port=8520
# 上傳文件總的最大值
spring.servlet.multipart.max-request-size=10MB
# 單個文件的最大值
spring.servlet.multipart.max-file-size=10MB

Linux中的shell通常是需要程序員自己寫一個方法實現對properties文件的讀取。以下是我寫的一個方法,親測有效,歡迎各位取用。

#讀取屬性文件指定鍵的值
get_value_of_properties_file() {
  result=""
  proFilePath="$1"
  key="$2"
    if [ "WJA${key}" = "WJA" ]; then
    echo "參數錯誤,未能指定有效Key。"
    echo "" >&2
    exit 1
  fi
  if [ ! -f ${proFilePath} ]; then
    echo "屬性文件(${proFilePath})不存在。"
    echo "" >&2
    exit 1
  fi
  if [ ! -r ${proFilePath} ]; then
    echo "當前用戶不具有對屬性文件(${proFilePath})的可讀權限。"
    echo "" >&2
    exit 1
  fi
  keyLength=$(echo ${key}|wc -L)
  lineNumStr=$(cat ${proFilePath} | wc -l)
  lineNum=$((${lineNumStr}))
  for ((i = 1; i <= ${lineNum}; i++)); do
    oneLine=$(sed -n ${i}p ${proFilePath})
    if [ "${oneLine:0:((keyLength))}" = "${key}" ] && [ "${oneLine:$((keyLength)):1}" = "=" ]; then
      result=${oneLine#*=}
      break
    fi
  done
  echo ${result}
}

使用示例: 方法名 properties文件路徑 key 。如get_value_of_properties_file /home/wja/test.properties server.port

總結

原文鏈接:https://blog.csdn.net/monarch91/article/details/123010625

欄目分類
最近更新