Shell中根据$1参数的值执行配置

在执行脚本时根据输入的参数来应用变量,并将变量的值输出到指定文件中:

写法一:

[root@localhost shyn]# cat shyn.sh 
#!/bin/bash
PRD_NTP_IP="10.119.72.45"
TST_NTP_IP="10.119.82.31"
IGW_NTP_IP="192.168.41.13"
if [ "$1" = "PRD" ];then
    echo $PRD_NTP_IP >/tmp/shyn/1
elif [ "$1" = "TST" ];then
    echo $TST_NTP_IP >/tmp/shyn/1
elif [ "$1" = "IGW" ];then
    echo $IGW_NTP_IP >/tmp/shyn/1
else
    echo "Please specify PRD or TST or IGW."
    exit 1
    #如果输入的参数无效,则退出脚本
fi

写法二:

[root@localhost shyn]# cat shyn.sh 
#!/bin/bash
if [ "$1" = "PRD" ];then
    VARIABLE=10.119.72.45
elif [ "$1" = "TST" ];then
    VARIABLE=10.119.82.31
elif [ "$1" = "TST" ];then
    VARIABLE=192.168.41.13
else
    echo "Please specify PRD or TST or IGW."
    exit 1
    #如果输入的参数无效,则退出脚本
fi
echo $VARIABLE >/tmp/shyn/1

执行结果

[root@localhost shyn]# sh shyn.sh PRD
[root@localhost shyn]# cat /tmp/shyn/1 
10.119.72.45
[root@localhost shyn]# sh shyn.sh TST
[root@localhost shyn]# cat /tmp/shyn/1 
10.119.82.31
[root@localhost shyn]# sh shyn.sh IGW
[root@localhost shyn]# cat /tmp/shyn/1 
192.168.41.13
[root@localhost shyn]# sh shyn.sh 1
Please specify PRD or TST or IGW.
[root@localhost shyn]# echo $?
1
[root@localhost shyn]# 

你可能感兴趣的:(Shell,linux,服务器,运维,shell)