首页 > 解决方案 > 在 bash 的命令行中查找重复的参数

问题描述

我正在寻找一种方法来查看命令行参数是否在 bash 中重复。

换句话说,当我这样做时,./imp.sh matches matches matches target我的程序必须发送一个错误,因为匹配重复了 3 次。(./imp.sh是程序的名称)。

我可以搜索正确数量的参数,但我看不到天气每个参数都是唯一的。

为了查看正确数量的参数,我这样做:

if [ "$#" -ne 4 ]; then
 echo "Incorrect number of parameters"
 exit 1
fi

标签: bashshellcommand-lineparameters

解决方案


如果您期望恰好三个唯一参数,则可以简单地检查详尽的可能性:

if [ $# -ne 4 ]; then
    ...
elif [ "$1" = "$2" ] || [ "$1" = "$3" ] || [ "$2" = "$3" ]; then
    echo "First three arguments must be unique"
    exit 1
fi

如果有任意数量的元素,则将关联数组的键用作集合。

declare -A unique

for arg in "${@:1:$#-1}"; do
    if [[ -v unique[$arg] ]]; then
        echo "Duplicate arg $arg"
        exit 1
    fi
    unique[$arg]=  # The value doesn't matter; the empty string is as good as any
done

推荐阅读