shell自定义参数名称的两种方式

第一种

使用getopts
命令示例:/bin/bash xxx.sh -i xxx -n xxx -g xxx -d xxx -h xxx

#!/bin/bash
# 获取参数
while getopts ":i:n:g:d:h:" opt
do
    case $opt in
        i)
        IPADDR=${OPTARG}
        ;;
        n)
        NETMASK=${OPTARG}
        ;;
        g)
        GATEWAY=${OPTARG}
        ;;
	d)
        DNS=${OPTARG}
        ;;
	h)
        HOSTNAME=${OPTARG}
        ;;
        ?)
        echo "未知参数"
        exit 1;;
    esac
done

# 配置默认参数
[ ! $IPADDR ]&&(echo "错误: 缺少必填参数-i,用于设置IP"&&exit 1)
[ ! $GATEWAY ]&&(echo "错误: 缺少必填参数-g,用于设置网关"&&exit 1)
[ ! $NETMASK ]&&NETMASK="255.255.255.0"
[ ! $DNS ]&&DNS="8.8.8.8;114.114.114.114"
[ ! $HOSTNAME ]&&HOSTNAME="template"

# 修改网络
sed -i "s/__ipaddr__/$IPADDR/g" /etc/sysconfig/network-scripts/ifcfg-eth0
sed -i "s/__netmask__/$NETMASK/g" /etc/sysconfig/network-scripts/ifcfg-eth0
sed -i "s/__gateway__/$GATEWAY/g" /etc/sysconfig/network-scripts/ifcfg-eth0
systemctl restart network

# 修改DNS
DNS_LIST=(${DNS//;/ }) 
for dns in ${DNS_LIST[@]}
do
   echo "nameserver $dns" >> /etc/resolv.conf
done

# 修改主机名
hostnamectl set-hostname $HOSTNAME

第二种

自定义切割,使用$@循环所有参数,实现方式灵活
命令示例:/bin/bash xxx.sh ipaddr=xxx netmask=xxx ...

#!/bin/bash
# 获取参数
function getArg() {
	for item in $@
	do
		[[ $item =~ "ipaddr" ]]&&IPADDR=`echo $item |cut -d = -f 2`	
		[[ $item =~ "netmask" ]]&&NETMASK=`echo $item |cut -d = -f 2`	
		[[ $item =~ "gateway" ]]&&GATEWAY=`echo $item |cut -d = -f 2`	
		[[ $item =~ "dns" ]]&&DNS=`echo $item |cut -d = -f 2`	
		[[ $item =~ "hostname" ]]&&HOSTNAME=`echo $item |cut -d = -f 2`
	done
}
getArg $@

# 配置默认参数
[ ! $IPADDR ]&&(echo "错误: 缺少必填参数ipaddr,用于设置IP"&&exit 1)
[ ! $GATEWAY ]&&(echo "错误: 缺少必填参数gateway,用于设置网关"&&exit 1)
[ ! $NETMASK ]&&NETMASK="255.255.255.0"
[ ! $DNS ]&&DNS="8.8.8.8;114.114.114.114"
[ ! $HOSTNAME ]&&HOSTNAME="template"

# 修改网络
sed -i "s/__ipaddr__/$IPADDR/g" /etc/sysconfig/network-scripts/ifcfg-eth0
sed -i "s/__netmask__/$NETMASK/g" /etc/sysconfig/network-scripts/ifcfg-eth0
sed -i "s/__gateway__/$GATEWAY/g" /etc/sysconfig/network-scripts/ifcfg-eth0
systemctl restart network

# 修改DNS
DNS_LIST=(${DNS//;/ }) 
for dns in ${DNS_LIST[@]}
do
   echo "nameserver $dns" >> /etc/resolv.conf
done

# 修改主机名
hostnamectl set-hostname $HOSTNAME