首页 > 解决方案 > 更新配置中的一行,如果不存在则添加它

问题描述

我需要编写一个 bash 脚本来检查 apache2 配置文件,如果存在则更新 2 个设置,如果不存在则添加它们。

我的 bash 技能并不出色,但我知道我需要使用 grep 来查找以尝试在文件中查找该行。但我不确定如何在文件中找到该行,然后如果密钥存在则只更新值部分。

我需要更新的设置是

ServerTokens Prod
ServerSignature Off

文件里面/etc/apache2/conf-available/security.conf

有人能帮忙吗?

标签: bashapacheshell

解决方案


我刚才有半个小时的空闲时间,所以我想试试这个。我试图在整个代码中注释,但如果您不确定,您可能想就特定位提出问题。

这依赖于 sed 的-i选项,我知道并非所有版本的 Sed 都附带该选项,所以这是一个限制,但它应该能让你继续前进。我已经在 MacOS Mojave 上编写了它。

它处理不正确的条目,跳过正确的条目,并允许您使用变量轻松更新文件名和配置选项。它还将输出状态。

#!/bin/bash -e

# The file on which to perform a "find and replace"
FILE="/etc/apache2/conf-available/security.conf"

# Use grep to find lines containing each required line
CHECK_SERVER_TOKENS=$(grep ^ServerTokens "$FILE")
CHECK_SERVER_SIGNATURE=$(grep ^ServerSignature "$FILE")

# Specify what the good config looks like.  This will be used in the find and replace.
TOKENCONFIG="ServerTokens Prod"
SIGNATURECONFIG="ServerSignature Off"

# If the grep above found no results, add the config in.
if [ -z "$CHECK_SERVER_TOKENS" ]; then
  echo "$TOKENCONFIG" >> "$FILE"
# If the grep above contains a result but it does not match desired config, replace it with desired config.
elif [ "$CHECK_SERVER_TOKENS" != "$TOKENCONFIG" ]; then
  # Use sed to "find and replace" wrong config, with desired config
  sed -i 's/'"$CHECK_SERVER_TOKENS"'/'"$TOKENCONFIG"'/g' "$FILE"
fi

# If the grep above found no results, add the config in
if [ -z "$CHECK_SERVER_SIGNATURE" ]; then
  echo "$SIGNATURECONFIG" >> "$FILE"
# If the grep above contains a result but it does not match desired config, replace it with desired config.
elif [ "$CHECK_SERVER_SIGNATURE" != "$SIGNATURECONFIG" ]; then
  # Use sed to "find and replace" wrong config, with desired config
  sed -i 's/'"$CHECK_SERVER_SIGNATURE"'/'"$SIGNATURECONFIG"'/g' "$FILE"
fi

service apache2 restart

推荐阅读