首页 > 服务器维护 > linux

shell脚本如何读取properties文件中的值

发布时间:2022-3-10 16:16 作者:巴山农夫

如下面代码所示的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

总结

到此这篇关于shell脚本如何读取properties文件中值的文章就介绍到这了,更多相关shell读取properties文件值内容请搜索猪先飞以前的文章或继续浏览下面的相关文章希望大家以后多多支持猪先飞!

原文出处:https://blog.csdn.net/monarch91/article/details/123010625

标签:[!--infotagslink--]

您可能感兴趣的文章: