bash - 在 bash 的命令行中查找重复的参数
问题描述
我正在寻找一种方法来查看命令行参数是否在 bash 中重复。
换句话说,当我这样做时,./imp.sh matches matches matches target
我的程序必须发送一个错误,因为匹配重复了 3 次。(./imp.sh
是程序的名称)。
我可以搜索正确数量的参数,但我看不到天气每个参数都是唯一的。
为了查看正确数量的参数,我这样做:
if [ "$#" -ne 4 ]; then
echo "Incorrect number of parameters"
exit 1
fi
解决方案
如果您期望恰好三个唯一参数,则可以简单地检查详尽的可能性:
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
推荐阅读
- c++ - 为什么 std::stream 操纵器基础结构中存在类型不一致?
- django - /etc/nginx/conf.d/default.conf:1 中不允许使用“http”指令
- reactjs - 使用 React 测试库按组件名称进行测试
- java - Java Socket 和 ServerSocket 通信死锁
- python - avro-python3 不提供模式演变?
- php - 我将如何解析一个存储在其中的字符串的 php 变量?
- node.js - 如何将环境变量从文件传递到节点命令
- python - 如何修复mysqlclient错误,无法下载,(wndows os)
- ios - 跟踪 iOS 应用的移动数据和 WiFi 使用情况
- aws-cloud9 - AWS-Cloud9 时间积累太快