shell脚本参数解析
  oIa1edJoFmXP 2023年11月02日 24 0
$0 #文件名
$1 #第一个参数
$2 #第二个参数
$* #所有参数的字符串
$@ #所有参数的数组

getopts(shell内置)

getopts不支持长参数(例如: 长: --help; 短:-h)
使用示例

function Usage(){
    echo "print help message"
}

#会处理-p -h -d三个参数
#p后面的冒号表示,-p后面是需要带参数的,-h和-d后面不带参数
while getopts "p:hd" arg
do
    case $arg in
    p)
        target_platform=$OPTARG
        #数据保存在变量{$OPTARG}中
        ;;
    h)
        Usage
        exit 1
        ;;
    d)
        echo "hello d"
        ;;
    ?)
        Usage
        #不在解析列表中的参数
        exit 1
        ;;
    esac
done

getopt(外部工具)

示例

#!/bin/bash

# A small example program for using the new getopt(1) program.
# This program will only work with bash(1)
# An similar program using the tcsh(1) script language can be found
# as parse.tcsh

# Example input and output (from the bash prompt):
# ./parse.bash -a par1 'another arg' --c-long 'wow!*\?' -cmore -b " very long "
# Option a
# Option c, no argument
# Option c, argument `more'
# Option b, argument ` very long '
# Remaining arguments:
# --> `par1'
# --> `another arg'
# --> `wow!*\?'

# Note that we use `"$@"' to let each command-line parameter expand to a
# separate word. The quotes around `$@' are essential!
# We need TEMP as the `eval set --' would nuke the return value of getopt.

#-o表示短选项,--long表示长选项
#一个冒号表示该选项有一个必选参数,空格和紧贴选项都行
#两个冒号表示该选项有一个可选参数,可选参数必须紧贴选项,如下例中-carg 而不能是-c arg

# -n:出错时打印的信息

# -- :举一个例子比较好理解:
#我们要创建一个名字为 "-f"的目录你会怎么办?
# mkdir -f #不成功,因为-f会被mkdir当作选项来解析,这时就可以使用
# mkdir -- -f 这样-f就不会被作为选项。

TEMP=`getopt -o ab:c:: --long a-long,b-long:,c-long:: \
     -n 'example.bash' -- "$@"`

if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi

# Note the quotes around `$TEMP': they are essential!
#set 会重新排列参数的顺序,也就是改变$1,$2...$n的值,这些值在getopt中重新排列过了
eval set -- "$TEMP"

#经过getopt的处理,下面处理具体选项。

while true ; do
        case "$1" in
                -a|--a-long) echo "Option a" ; shift ;;
                -b|--b-long) echo "Option b, argument \`$2'" ; shift 2 ;;
                -c|--c-long)
                    # c has an optional argument. As we are in quoted mode,
                    # an empty parameter will be generated if its optional
                    # argument is not found.
                    case "$2" in
                            "") echo "Option c, no argument"; shift 2 ;;
                            *)  echo "Option c, argument \`$2'" ; shift 2 ;;
                    esac ;;
                --) shift ; break ;;
                *) echo "Internal error!" ; exit 1 ;;
        esac
done
echo "Remaining arguments:"
for arg do
   echo '--> '"\`$arg'" ;
done

shell脚本处理长参数的模板

一个shell模板,处理命令行参数,支持长短参数:

#!/bin/bash
#
# FILE: kvm-clone-v2.sh
#
# DESCRIPTION: Clone a RHEL5.4/RHEL6 kvm guest on ubuntu14.04 host superv.
#     This shell is used for cloning RHEL5.4 or RHEL6.x KVM guest.
#     Note this shell is only tested for host OS Ubuntu14.04 and RHEL6.4.
#
#     KVM is short for Kernel-based Virtual Machine and makes use of
#     hardware virtualization. You need a CPU that supports hardware
#     virtualization, e.g. Intel VT or AMD-V.
#
# NOTES: This requires GNU getopt.
#        I do not issue any guarantee that this will work for you!
#
# COPYRIGHT: (c) 2015-2016 by the ZhangLiang
#
# LICENSE: Apache 2.0
#
# ORGANIZATION: PepStack (pepstack.com)
#
# CREATED: 2015-05-22 12:34:00
#
#=======================================================================
_file=$(readlink -f $0)
_dir=$(dirname $_file)
. $_dir/common.sh

# Treat unset variables as an error
set -o nounset

__ScriptVersion="2015.05.22"
__ScriptName="kvm-clone-v2.sh"


#-----------------------------------------------------------------------
# FUNCTION: usage
# DESCRIPTION:  Display usage information.
#-----------------------------------------------------------------------
usage() {
    cat << EOT

Usage :  ${__ScriptName} CFGFILE [OPTION] ...
  Create a virtual machine from given options.

Options:
  -h, --help                    Display this message
  -V, --version                 Display script version
  -v, --verbose
  -o, --origver=ORIGVER         Origin vm name with version: rhel5_4 | rhel6_4
  -D, --disksize=DISKSIZE       Origin vm disk size: compact|medium|large
  -p, --path-prefix=PATH        Path prefix of vm
  -m, --memsize=SIZEMB          Memory size of vm by MB: 8192
  -c, --vcpus=VCPUS             Number of virtual cpu cores: 4
  -n, --vmname=VMNAME           Given name of vm
  -H, --domain<DOMAIN>          Optional hostname suffix of vm
  -i, --ipv4=IPADDR             Static ipv4 addr of vm if used
  -S, --supervisor=SUPERVISOR   Supervisor of vm: rhel6.4 or ubuntu14.04
  -G, --gateway=GATEWAY         Gateway ipv4 address
  -T, --iftype=IFTYPE           Network type: bridge or default
  -B, --broadcast=BCAST         Broadcast inet addr
  -M, --netmask=MASK            Net mask address, default: 255.255.255.0

Exit status:
  0   if OK,
  !=0 if serious problems.

Example:
  1) Use short options to create vm:
    $ sudo $__ScriptName ../conf/kvm-origin.cfg -o rhel6_4 -D compact -p el6 -m 2048 -c 2 -n vm-test2 -H pepstack.com -i 192.168.122.61 -S ubuntu14.04 -G 192.168.122.1 -B 192.168.122.255 -M 255.255.255.0

  2) Use long options to create vm:
    $ sudo $__ScriptName ../conf/kvm-origin.cfg --origver=rhel6_4 --disksize=compact --path-prefix=el6 --memsize=2048 --vcpus=2 --vmname=vm-test3 --domain=pepstack.com --ipv4=192.168.122.63 --supervisor=ubuntu14.04 --gateway=192.168.122.1 --broadcast=192.168.122.255 --netmask=255.255.255.0

Report bugs to 350137278@qq.com

EOT
}   # ----------  end of function usage  ----------

if [ $# -eq 0 ]; then usage; exit 1; fi

ABSDIR=$(real_path $(dirname $0))

CFGFILE=
VMNAME=
DOMAIN=
IPADDR=
PATHPREFIX=
GATEWAY=
BDCAST=
NETMASK="255.255.255.0"
VERBOSE=false
SIZEMB=8192
VCPUS=4
ORIGVER="rhel6_4"
DISKSIZE="compact"
VMORIG="$ORIGVER:$DISKSIZE"
SUPERVISOR="ubuntu14.04"

# parse options:
RET=`getopt -o hVvo:D:p:m:c:n:H::i:S:G:T:B:M: \
--long help,version,verbose,origver:,disksize:,path-prefix:,memsize:,\
vcpus:,vmname:,domain::,ipv4:,supervisor:,gateway:,\
iftype:,broadcast:,netmask:\
  -n ' * ERROR' -- "$@"`

if [ $? != 0 ] ; then echoerror "$__ScriptName exited with doing nothing." >&2 ; exit 1 ; fi

# Note the quotes around $RET: they are essential!
eval set -- "$RET"

# set option values
while true; do
    case "$1" in
        -h | --help ) usage; exit 1;;
        -v | --verbose ) VERBOSE=true; shift ;;
        -V | --version ) echoinfo "$(basename $0) -- version $__ScriptVersion"; exit 1;;

        -o | --origver ) ORIGVER=$2
            echoinfo "origin: $ORIGVER"
            shift 2 ;;

        -D | --disksize ) DISKSIZE=$2
            echoinfo "origin size: $DISKSIZE"
            shift 2 ;;

        -p | --path-prefix ) PATHPREFIX=$2
            echoinfo "subdir: $PATHPREFIX"
            shift 2 ;;

        -n | --vmname) VMNAME=$2
            echoinfo "new vm name: $VMNAME"
            shift 2 ;;

        -H | --domain)
            # domain-suffix has an optional argument. as we are in quoted mode,
            # an empty parameter will be generated if its optional argument is not found.
            case "$2" in
                    "" ) echowarn "--domain, no argument"; shift 2 ;;
                    * )  DOMAIN="$2" ; echoinfo "domain: $DOMAIN"; shift 2 ;;
            esac ;;

        -i | --ipv4) IPADDR=$2
            echoinfo "static ipv4: $IPADDR"
            shift 2 ;;

        -m | --memsize ) SIZEMB=$2
            echoinfo "memory: $SIZEMB mb"
            shift 2 ;;

        -c | --vcpus ) VCPUS=$2
            echoinfo "cpu cores: $VCPUS"
            shift 2 ;;

        -S | --supervisor ) SUPERVISOR=$2
            echoinfo "supervisor: $SUPERVISOR"
            shift 2;;

        -G | --gateway ) GATEWAY=$2
            echoinfo "gateway: $GATEWAY"
            shift 2 ;;

        -T | --iftype ) IFTYPE=$2
            echoinfo "network type: $IFTYPE"
            shift 2 ;;

        -B | --broadcast ) BDCAST=$2
            echoinfo "broad cast: $BDCAST"
            shift 2 ;;

        -M | --netmask) NETMASK=$2
            echoinfo "netmask: $NETMASK"
            shift 2 ;;

        -- ) shift; break ;;
        * ) echoerror "internal error!" ; exit 1 ;;
     esac
done

# config file must provided with remaining argument
for arg do
    CFGFILE=$(real_path $(dirname $arg))'/'$(basename $arg)
done

if [ -f $CFGFILE ]; then
    echoinfo "Config file: $CFGFILE"
else
    echoerror "Config file not found: $CFGFILE"
    exit 3
fi

##################### THIS IS ONLY A TEMPLATE SHELL FILE #####################


【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
oIa1edJoFmXP