San*_*ram 7 shell app-config sh readfile
我是shell脚本的新手.我有一个文件app.conf:
[MySql]
user = root
password = root123
domain = localhost
database = db_name
port = 3306
[Logs]
level = logging.DEBUG
[Server]
port = 8080
Run Code Online (Sandbox Code Playgroud)
我想在shell脚本中解析这个文件,并希望从中提取mysql凭据.我怎样才能做到这一点?
我这样做:
pw=$(awk '/^password/{print $3}' app.conf)
user=$(awk '/^user/{print $3}' app.conf)
echo $pw
root123
echo $user
root
Run Code Online (Sandbox Code Playgroud)
在$()将变量pw里面的命令的输出.内部命令查看app.conf文件中的行开始password,然后在该行中打印第3个字段.
EDITED
如果要从配置文件中解析出一堆值,我会为配置文件名创建一个变量:
CONFIG=app.conf
pw=$(awk '/^password/{print $3}' "${CONFIG}")
user=$(awk '/^user/{print $3}' "${CONFIG}")
Run Code Online (Sandbox Code Playgroud)
以下是如何执行两个不同的端口...当您到达右侧部分时将标志设置为1,并在找到端口时退出.
mport=$(awk '/^\[MySQL\]/{f=1} f==1&&/^port/{print $3;exit}' "${CONFIG}")
sport=$(awk '/^\[Server\]/{f=1} f==1&&/^port/{print $3;exit}' "${CONFIG}")
Run Code Online (Sandbox Code Playgroud)
您将要搜索“shell ini 文件解析器”。我会从这样的事情开始:
ini_get () {
awk -v section="$2" -v variable="$3" '
$0 == "[" section "]" { in_section = 1; next }
in_section && $1 == variable {
$1=""
$2=""
sub(/^[[:space:]]+/, "")
print
exit
}
in_section && $1 == "" {
# we are at a blank line without finding the var in the section
print "not found" > "/dev/stderr"
exit 1
}
' "$1"
}
mysql_user=$( ini_get app.conf MySql user )
Run Code Online (Sandbox Code Playgroud)
使用 awk:
awk -F ' *= *' '$1=="user"||$1=="password"{print $2}' my.cnf
root
gogslab
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11153 次 |
| 最近记录: |