你如何使用 getopts?

发布于 2024-12-08 00:47:50 字数 356 浏览 0 评论 0原文

bash 脚本中使用 getopts 的最简单、最直接的方法是什么?

如果我有一个名为:myscript 的脚本,并且它可以采用参数:-p -r -s -x

if argument x then exit
if argument p then echo "port 10"
if argument s then add 2+2
if argument r then echo env 

这是一个假设的脚本但我只想看一个如何完成此操作的示例。

what is the easiest, most straight forward, way to use getopts in bash script.

if i have a script called: myscript and it CAN take the the arguments: -p -r -s -x

if argument x then exit
if argument p then echo "port 10"
if argument s then add 2+2
if argument r then echo env 

This is a hypothetical script but I would just like to see an example of how this would be done.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

哽咽笑 2024-12-15 00:47:50
while getopts :xpsr opt; do
   case $opt in
     x ) exit                                ;;
     p ) echo port 10                        ;;
     s ) (( 2 + 2 ))                         ;;
     r ) echo env                            ;;
    \? ) echo "${0##*/}" [ -xpsr ]; exit 1   ;;
  esac
done
while getopts :xpsr opt; do
   case $opt in
     x ) exit                                ;;
     p ) echo port 10                        ;;
     s ) (( 2 + 2 ))                         ;;
     r ) echo env                            ;;
    \? ) echo "${0##*/}" [ -xpsr ]; exit 1   ;;
  esac
done
兮子 2024-12-15 00:47:50
usage()
{
    echo "Usage: $0 [-o <offset>] [-h];"
    exit 0;
}

# -o (offset) need a value
# -h prints help
offset=0    # 0 is default offset

while getopts o:s opt
do
    case "$opt" in
    d)  offset="$OPTARG";; # changing offset
    s)  usage              # calls function "usage"
    \?) echo "$OPTARG is an unknown option"
        exit 1;; # all other options
    esac
done

shift $((OPTIND-1))
usage()
{
    echo "Usage: $0 [-o <offset>] [-h];"
    exit 0;
}

# -o (offset) need a value
# -h prints help
offset=0    # 0 is default offset

while getopts o:s opt
do
    case "$opt" in
    d)  offset="$OPTARG";; # changing offset
    s)  usage              # calls function "usage"
    \?) echo "$OPTARG is an unknown option"
        exit 1;; # all other options
    esac
done

shift $((OPTIND-1))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文