Aru*_*noy 6 scripting bash sed shell-script
我有一个包含部分数据的配置文件,如下所述。使用 shell 脚本访问每个变量。我正在使用 sed 命令来实现这一点,现在我面临一个问题,比如如果我忘记配置一个变量示例:名称 [APP1] 它将采用 [APP2] 名称。
配置文件:
[APP1]
name=Application1
StatusScript=/home/status_APP1.sh
startScript=/home/start_APP1.sh
stopScript=/home/stop_APP1.sh
restartScript=/home/restart.APP1.sh
[APP2]
name=Application2
StatusScript=/home/status_APP2.sh
startScript=/home/start_APP2.sh
stopScript=/home/stop_APP2.sh
restartScript=/home/restart.APP2.sh
logdir=/log/APP2/
.
.
.
.
.
[APPN]
name=ApplicationN
StatusScript=/home/status_APPN.sh
startScript=/home/start_APPN.sh
stopScript=/home/stop_APPN.sh
restartScript=/home/restart.APPN.sh
logdir=/log/APPN
Run Code Online (Sandbox Code Playgroud)
shell 命令使用:
sed -nr "/^\[APP1\]/ { :l /^name[ ]*=/ { s/.*=[ ]*//; p; q;}; n; b l;}"
Run Code Online (Sandbox Code Playgroud)
有没有办法解决这个问题,如果某个部分下没有配置某个变量,则通过 null 或 0 作为变量值。
小智 3
您可以创建一个像这样的 shell 函数:
printSection()
{
section="$1"
found=false
while read line
do
[[ $found == false && "$line" != "[$section]" ]] && continue
[[ $found == true && "${line:0:1}" = '[' ]] && break
found=true
echo "$line"
done
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以像命令一样使用 printSection ,并将该部分作为参数传递,如下所示:
printSection APP2
Run Code Online (Sandbox Code Playgroud)
要获取参数,您现在可以使用更简单的 sed,例如:
printSection APP2 | sed -n 's/^name=//p'
Run Code Online (Sandbox Code Playgroud)
这将在标准输入上运行并写入标准输出。因此,如果您的示例配置文件名为 /etc/application.conf,并且您想将 APP2 的名称存储在变量 app2name 中,您可以这样写:
app2name=$(printSection APP2 | sed -n 's/^name//p/' < /etc/applications.conf)
Run Code Online (Sandbox Code Playgroud)
或者,您可以将参数部分构建到函数中并完全跳过 sed,如下所示:
printValue()
{
section="$1"
param="$2"
found=false
while read line
do
[[ $found == false && "$line" != "[$section]" ]] && continue
[[ $found == true && "${line:0:1}" = '[' ]] && break
found=true
[[ "${line%=*}" == "$param" ]] && { echo "${line#*=}"; break; }
done
}
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样分配你的变量:
app2name=$(printValue APP2 name < /etc/applications.conf)
Run Code Online (Sandbox Code Playgroud)