脚本的名称是InstallmDNS.sh
脚本内容如下:
#!/bin/bash
sethostname() {
if [ $# -eq 1 ]
then
hostnamectl set-hostname "$1"
sed -i "/127.0.1.1/d" /etc/hosts
sed -i "/127.0.0.1/a\127.0.1.1 $1" /etc/hosts
reboot
else
echo "The exapmle of execute the script: bash InstallmDNS.sh server1"
echo "This script is executed with one parameter."
exit 0
fi
}
dia=`systemctl status avahi-daemon|grep Active`
if [[ "$dia" =~ "running" ]]
then
echo "mDNS is running"
sethostname
else
apt-get install avahi-daemon -y
echo "mDNS installation complete."
sethostname
fi
我运行脚本:
root@linux:/home/ankon# bash InstallmDNS.sh
mDNS is running
The exapmle of execute the script: bash InstallmDNS.sh server1
This script is executed with one parameter.
我使用参数运行脚本:
root@linux:/home/ankon# bash InstallmDNS.sh server2
mDNS is running
The exapmle of execute the script: bash InstallmDNS.sh server1
This script is executed with one parameter.
我添加了参数并运行了脚本,但参数没有执行任何操作,是什么原因造成的?我该如何修复它?
答案1
将参数传递给脚本与将参数传递给脚本内的函数不同。
提供给脚本的参数不会“自动传递”给函数。
您期望 $1 是server2
您传递给脚本的值,但实际上您在调用该函数时没有向该函数传递任何参数
if [[ "$dia" =~ "running" ]]
then
echo "mDNS is running"
sethostname <---- This line should pass the arguments
else
apt-get install avahi-daemon -y
echo "mDNS installation complete."
sethostname <---- This line should pass the arguments
fi
指出的行应更改为
sethostname $1