要在 CentOS 中用脚本设置主机名,您可以使用以下步骤:
set_hostname.sh
:touch set_hostname.sh
#!/bin/bash
# 检查是否提供了主机名参数
if [ -z "$1" ]; then
echo "Usage: $0 <new_hostname>"
exit 1
fi
# 设置新的主机名
new_hostname="$1"
# 检查主机名是否有效
if ! hostnamectl set-hostname "$new_hostname" --static; then
echo "Error: Failed to set the hostname."
exit 2
fi
echo "Hostname has been successfully set to $new_hostname."
保存并关闭文件。
通过运行以下命令使脚本可执行:
chmod +x set_hostname.sh
现在,您可以通过提供一个新主机名作为参数来运行此脚本,如下所示:
./set_hostname.sh my_new_hostname
这将把您的 CentOS 主机名更改为 my_new_hostname
。请注意,更改主机名可能需要重新启动网络服务或计算机以生效。