将参数传递给带有空格的KSH脚本

问题描述 投票:0回答:1

我需要按如下所示将字串传递给KSH脚本

  $ script.sh -p "a b c"

我希望看到以下内容

  PARMS a b c 

但是当我尝试打印$ PARMS的值时,只有第一个单词单词“ a”打印出来

    #!/bin/ksh

    ARGS=`getopt p: $*`

    set -- $ARGS

    for i
    do
       case "$i"
       in
        -p)     PARMS=$2; shift; shift;;
        --)     shift; break;;
    esac
    done

    echo "PARMS" "${PARMS}"
linux shell ksh
1个回答
0
投票

这是ksh中getopts用法的示例。

#!/bin/ksh

DEFAULT_SITE_NAME="a.b.c.d"

SITE_NAME=$DEFAULT_SITE_NAME

USAGE="[-author?Andre Gelinas]"
USAGE+="[-copyright?2020]"
USAGE+="[+NAME?getopts.sh --- Example of getopts]"
USAGE+="[+DESCRIPTION?Example of getopts usage in ksh.]"
USAGE+="[s:site]:?[site:=$DEFAULT_SITE_NAME?Site name.]"
USAGE+="[p:param]:[param?Parameters to test.]"
USAGE+=$'[+SEE ALSO?\aMAN Page\a(1)]'

while getopts "$USAGE" optchar ; do
    case $optchar in
    p)  PARAM_TO_PRINT=$OPTARG ;;
    s)  SITE_NAME=$OPTARG ;;
    esac
done

print "Paramters [p] : "$PARAM_TO_PRINT
print "Site [s] : "$SITE_NAME

它支持短(-p)和长(--param =)类型的选项。 -s仅作为带有默认值的可选选项的示例。它还支持--help和--man的用法。

示例:

$ ./getopts.sh --param="a b c" --site=t.t.t.t
Paramters [p] : a b c
Site [s] : t.t.t.t
$ ./getopts.sh -p "a b c"
Paramters [p] : a b c
Site [s] : a.b.c.d
© www.soinside.com 2019 - 2024. All rights reserved.