该脚本的名称是 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
$#
函数中包含传递给函数的参数数量,而不是传递给整个脚本的参数数量。您可以执行sethostname "$@"
将所有脚本参数传递给函数,然后参数数量将按预期工作。