bash - 没有可选参数的 GETOPTS 情况

标签 bash

您好,我正在尝试找到一种方法,使 getopts 能够使用非预期的可选参数

我有一个带有可选参数的脚本

script.sh [-a] [-b] [-c | -d] file

我可以像这样使用 -a..-d

while geopts abc:abd opt
do 
case $opt in
a) do this ;;
b) do this ;;
...

..等等

我想让它可以在没有这些参数的情况下工作,这样我就可以像这样运行它

script.sh file

有没有办法制作一个新的案例选项,或者我需要用其他方式来做,谢谢大家的帮助,我是 bash 的初学者。

最佳答案

我以前做过这样的事情:

declare -A have=([a]=false [b]=false [c]=false [d]=false)

while geopts :abcd opt; do 
    case $opt in
        a) have[a]=true ;;
        b) have[b]=true ;;
        c) have[c]=true ;;
        d) have[d]=true ;;
        ?) echo "illegal option: -$OPTARG"; exit 1;;
    esac
done
shift $((OPTIND-1))

if ${have[c]} && ${have[d]}; then 
    echo "cannot give both -c and -d"
    exit 1
fi

${have[a]} && do_a_stuff
${have[b]} && do_b_stuff
...

该 case 语句是相当令人震惊的剪切粘贴编程:加强它:

while geopts :abcd opt; do 
    case $opt in
        a|b|c|d) have[$opt]=true ;;
        ?) echo "illegal option: -$OPTARG"; exit 1;;
    esac
done

关于bash - 没有可选参数的 GETOPTS 情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22596840/

相关文章:

bash - jq解析中如何使用环境变量参数

linux - GNU 并行 : execute one command parallel for all files in a folder

linux - sed 的 'N' 命令间歇性工作

linux - 为什么在先前的命令在Linux中完成之前执行此Shell命令?

bash - 在 tar 发生之前重命名目录名称

bash - 在 Bash 中循环使用空格的目录

Git可以 pull 好但不能推送 "could not read username"

linux - 如何将 LANG 设置为 ascii?

c - 读取c中的删除按键

linux - Unix,替换错误错误?