首页 > 解决方案 > 可以混合选项和参数吗?

问题描述

是否可以混合选项(使用 getopts)和参数($1....$10)?

标签: bashgetopts

解决方案


getopt(单数)可以处理混合的选项和参数,以及短选项-s和长--long选项以及--结束选项处理。

在这里查看如何file1file2选项混合并将它们分开:

$ args=(-ab opt file1 -c opt file2)
$ getopt -o ab:c: -- "${args[@]}"
 -a -b 'opt' -c 'opt' -- 'file1' 'file2'

典型用法如下:

#!/bin/bash

options=$(getopt -o ab:c: -l alpha,bravo:,charlie: -- "$@") || exit
eval set -- "$options"

# Option variables.
alpha=0
bravo=
charlie=

# Parse each option until we hit `--`, which signals the end of options.
# Don't actually do anything yet; just save their values and check for errors.
while [[ $1 != -- ]]; do
    case $1 in
        -a|--alpha)   alpha=1;    shift 1;;
        -b|--bravo)   bravo=$2;   shift 2;;
        -c|--charlie) charlie=$2; shift 2;;

        *) echo "bad option: $1" >&2; exit 1;;
    esac
done

# Discard `--`.
shift

# Here's where you'd actually execute the options.
echo "alpha:   $alpha"
echo "bravo:   $bravo"
echo "charlie: $charlie"

# File names are available as $1, $2, etc., or in the "$@" array.
for file in "$@"; do
    echo "file: $file"
done

推荐阅读