#!/bin/bash
set -e
exit_script(){
exit 1
}
if [ “$#”=0 ]; then
echo “参数错误,命令格式为: https://www.jb51.net/article/config.sh configfile”
exit_script
else
configPath=$1
fi
function get_line_num(){
local configKey=$1
grep -n -E ‘^\[‘ ${configPath} |grep -A 1 “\[${configKey}\]”|awk -F ‘:’ ‘{print $1}’|xargs
}
function get_config(){
#local configPath=$1
local configKey=$1
local configName=$2
local line_num=$(get_line_num $configKey)
local startLine=$(echo $line_num |awk ‘{print $1}’)
local endLine=$(echo $line_num|awk ‘{print $2}’)
if [ ${endLine} ];then
sed -n “${startLine},${endLine} s/${configName}=//p” ${configPath}
else
sed -n “${startLine},$ s/${configName}=//p” ${configPath}
fi
}
if [ -f $configPath ];then
MYSQL_DB_HOST=$(get_config MYSQL DB_HOST)
else
echo ${configPath}”文件不存在,请检查配置文件是否存在”
exit_script
fi
MYSQL_DB_PASSWD=$(get_config MYSQL DB_PASSWD)
MYSQL_DB_USER=$(get_config MYSQL DB_USER)
REDIS_DB_HOST=$(get_config REDIS DB_HOST)
REDIS_DB_PASSWD=$(get_config REDIS DB_PASSWD)
MYSQL_DB_HOST=$(sed -r -n ‘s/(^MYSQL_DB_HOST=)(.*)$/\2/p’ $configPath)
MYSQL_DB_NAME=$(sed -r -n ‘s/(^MYSQL_DB_NAME=)(.*)$/\2/p’ $configPath)
INIT_SQL=$(sed -r -n ‘s/(^MYSQL_INIT_SQL=)(.*)$/\2/p’ $configPath)
echo “MYSQL_DB_HOST=”${MYSQL_DB_HOST}
echo “MYSQL_DB_PASSWD=”${MYSQL_DB_PASSWD}
echo “MYSQL_DB_USER=”${MYSQL_DB_USER}
echo “REDIS_DB_HOST=”${REDIS_DB_HOST}
echo “REDIS_DB_PASSWD=”${REDIS_DB_PASSWD}
echo “—————–分割线————-”
echo “使用sed读取配置:MYSQL_DB_HOST=”${MYSQL_DB_HOST}
echo “使用sed读取配置:MYSQL_DB_NAME=”${MYSQL_DB_NAME}
echo “使用sed读取配置:MYSQL_INIT_SQL=”${INIT_SQL}