-1

问题

我有一个脚本,其中包含我希望根据变量的值执行的 case 语句。case 语句似乎要么忽略该值,要么不正确评估它,而是放弃为默认值。

情景

我从我们的服务器主机名中提取了一个特定字符,它指示服务器在我们环境中的位置。我们有六个不同的地点:

  • 管理(m):作为基础设施一部分的服务器,例如监控、电子邮件、票务等
  • Development(d):用于开发代码和应用程​​序功能的服务器
  • Test(t):用于初始测试代码和应用程​​序功能的服务器
  • 实施(i):将代码推送到用于生产前评估的服务器
  • 生产(p):不言自明
  • 服务:客户需要集成的服务器,在他们的项目中提供功能。这些与管理服务器是分开的,因为它们是客户服务器,而管理服务器由我们拥有和运营。

从主机名中提取字符后,我将其传递给 case 块。我希望 case 块能够评估字符并将几行文本添加到我们的 rsyslog.conf 文件中。发生的事情是 case 块返回默认值,除了告诉构建服务器的人由于无法识别的字符而手动配置条目之外什么都不做。

我已经针对我最近构建的服务器手动对此进行了测试,并验证了我从主机名(一个's')中提取的字符是预期的并且在案例块中占了。

编码

# Determine which environment our server resides in
host=$(hostname -s)
env=${host:(-8):1}
OLDFILE=/etc/rsyslog.conf
NEWFILE=/etc/rsyslog.conf.new

# This is the configuration we need on every server regardless of environment
read -d '' common <<- EOF 
...
TEXT WHICH IS ADDED TO ALL CONFIG FILES REGARDLESS OF FURTHER CODE EXECUTION
SNIPPED
....
EOF

# If a server is in the Management, Dev or Test environments send logs to lg01
read -d '' lg01conf <<- EOF
# Relay messages to lg01
*.notice @@xxx.xxx.xxx.100
#### END FORWARDING RULE ####
EOF

# If a server is in the Imp, Prod or is a non-affiliated Services zone server send logs to lg02
read -d '' lg02conf <<- EOF
# Relay messages to lg02
*.notice @@xxx.xxx.xxx.101
#### END FORWARDING RULE ####
EOF

# The general rsyslog configuration remains the same; pull it out and write it to a new file
head -n 63 $OLDFILE > $NEWFILE

# Add the common language to our config file
echo "$common" >> $NEWFILE

# Depending on which environment ($env) our server is in, add the appropriate
# remote log server to the configuration with the $common settings.
case $env in
    m) echo "$lg01conf" >> $NEWFILE;;
    d) echo "$lg01conf" >> $NEWFILE;;
    t) echo "$lg01conf" >> $NEWFILE;;
    i) echo "$lg02conf" >> $NEWFILE;;
    p) echo "$lg02conf" >> $NEWFILE;;
    s) echo "$lg02conf" >> $NEWFILE;;
    *) echo "Unknown environment; Manually configure"
esac

# Keep a dated backup of the original rsyslog.conf file
cp $OLDFILE $OLDFILE.$(date +%Y%m%d)
# Replace the original rsyslog.conf file with the new version
mv $NEWFILE $OLDFILE

旁白

我已经确定我可以使用 | 将 case 块中的不同代码组组合成单行(总共两行)。操作员。我已经按照上面的方式列出了它,因为这是我遇到问题时它的编码方式。

4

1 回答 1

1

我看不出你的代码有什么问题。也许;;在默认子句中添加另一个。要找到问题,请添加 aset -vx作为第一行。会显示很多调试信息。

于 2013-03-29T11:05:38.433 回答