【发布时间】:2019-06-24 09:10:56
【问题描述】:
我正在创建一个脚本,以便让我的组织更轻松地将工作站添加到我们的 Nagios 监控系统。
每次脚本运行时,我都希望能够输入主机名、别名和地址(作为用户输入的变量),并在 sed 命令中调用这些变量,以便“创建”一个新的主机速度要快得多,然后全部输入。
我正在尝试在 sed 找到之后添加整个字符串 "主机地址}"
我认为是 /a (在找到所述字符串后追加) 尽管如此,使用双引号仍然不允许调用变量。
#!bin/bash
# Prompt for hostname, alias, and IP address of new host
# take user input has variable to be used in sed
# Takes user input for hostname
echo host_name :
read var_hostname
# Takes user input for alias
echo alias :
read var_alias
# Takes user input for ip address
echo address :
read var_address
# searches for the top-most instance "address of the host" within the windows.cfg file
# after said instance is found, appends the new string below, which calls for the variables received
# previously by user
sed -i -e " address of the host } /a
define host{
use windows-server ; Inherit default values from a template
host_name $var_hostname ; The name we are giving to this host
alias $var_alias ; A longer name associated with the host
address $var_address ; IP address of the host
}"
windows.cfg
我希望将字符串“define host{}”与用户输入的变量一起写入文件中。而不是
【问题讨论】:
-
变量总是用双引号代替,我看不出它在这里不起作用的任何原因。如果用文字字符串替换变量是否有效?
-
address of the host} a应该是/address of the host/a -
我尝试使用 /option/ 但这否定了变量。现在正在调用变量......但是当我运行脚本时我收到了这个:表达式#1,char 28:命令后的额外字符
-
如果你想查看 shell 脚本在做什么,请将
set -x放在开头。然后它将显示所有正在执行的命令,并填充变量。 -
@Allan 是的,您的解释写得非常好,有助于澄清分配。我还按照建议完成了 -x 命令,以查看该命令实际上在做什么,这很有用。脚本运行没有错误...但 windows.cfg 文件没有变化。