Linux Bash脚本如何分离单横杠与双横杠参数?
问题解决:Bash脚本参数分组及
[[: not found]]错误修复 错误原因
[[: not found]]报错是因为你用了Bash专属的[[扩展语法,但脚本可能被sh(POSIX Shell)执行——sh不支持[[语法。另外原脚本还存在两个逻辑问题:
- 变量名搞反:你需要group1存单横杠参数,group2存双横杠参数,但原脚本把双横杠参数放到了g1;
- 未处理短参数的后续值:比如
-a 1中的1会被误分到group2,而不是和-a一起留在group1。
修正后的脚本
用Bash数组存储分组(避免参数含空格时的拆分问题),同时处理短参数的关联值,脚本开头指定Bash解释器确保语法兼容:
#!/bin/bash # 用数组存储分组,比字符串拼接更安全 group1=() group2=() # 用索引遍历,方便处理短参数的后续值 index=1 while [ $index -le $# ]; do current_arg="${!index}" if [[ $current_arg == --* ]]; then # 双横杠开头的参数,加入group2 group2+=("$current_arg") ((index++)) elif [[ $current_arg == -* && $current_arg != --* ]]; then # 单横杠开头的参数,加入group1 group1+=("$current_arg") ((index++)) # 检查下一个参数是否是当前短参数的取值(非横杠开头) if [ $index -le $# ]; then next_arg="${!index}" if [[ $next_arg != -* ]]; then group1+=("$next_arg") ((index++)) fi fi else # 非横杠开头的独立参数,可根据需求自行处理(这里跳过) ((index++)) fi done # 输出分组结果 echo "group1: ${group1[*]}" echo "group2: ${group2[*]}"
测试验证
执行命令:
./your_script.sh -a 1 --b=3 -c 7 --d=8
输出结果:
group1: -a 1 -c 7 group2: --b=3 --d=8
补充说明
- 如果必须兼容POSIX Shell(不能用
[[和数组),可以改用字符串拼接+[语法,但要注意参数含空格的情况:
但这种方式在参数含空格时会出现问题,推荐优先使用Bash版本。#!/bin/sh group1="" group2="" index=1 while [ $index -le $# ]; do current_arg=$(eval echo "\$$index") if [ "$current_arg" = --* ]; then group2="$group2 $current_arg" index=$((index+1)) elif [ "$current_arg" = -* ] && [ "$current_arg" != -- ]; then group1="$group1 $current_arg" index=$((index+1)) if [ $index -le $# ]; then next_arg=$(eval echo "\$$index") if [ "$next_arg" != -* ]; then group1="$group1 $next_arg" index=$((index+1)) fi fi else index=$((index+1)) fi done echo "group1: $group1" echo "group2: $group2"
内容的提问来源于stack exchange,提问作者Ahmad
相关产品推荐
相关产品推荐

