约 17071 字

约 85 分钟

#Bash 的 getopt 命令

getopt [OPTIONS] -- PARAMETERS

功能

解析命令行参数。

类型

可执行文件(/usr/bin/getopt),属于 util-linux。

参数

  • OPTIONS 选项:
    • -a, --alternative - 允许长选项使用单个横线
    • -l, --longoptions OPTIONS - 要识别的长选项列表,用逗号分隔,用冒号表示选项需要附带参数
    • -n, --name NAME - 打印错误消息时以 NAME 作为程序的名称
    • -o, --options OPTIONS - 要识别的短选项列表,用冒号(:)后缀表示选项需要附带参数;无此选项则以首个参数作为此选项的值
    • -q, --quiet - 不打印错误消息
    • -Q, --quiet-output - 不打印常规输出
    • -s, --shell SHELL - 按照 SEHLL 的需要生成引号;默认为 BASH
    • -T, --test - 检测 getopt 命令是否为增强版本
    • -u, --unquoted - 不对输出添加引号
    • --help - 显示帮助
    • --version - 显示版本
  • PARAMETERS - 要解析的参数列表

#示例

短选项

$ getopt -o f:hv -- -f file other_args
 -f 'file' -- 'other_args'
$ getopt -o f:hv -- -f file other_args -h
 -f 'file' -h -- 'other_args'
  • f:hv 表示接受 -f,-h,-v 三个选项,其中 -f 需要附带参数

长选项

$ getopt -o '' -l input:,output: -- --input file1 --output file2 other_args
 --input 'file1' --output 'file2' -- 'other_args'
  • -o '' 表示没有短选项,如果不这样设置,则会将 --input 当作短选项列表

在脚本文件中使用

#!/bin/bash

# 解析参数,报告错误时以 $0 为名
PARSED=$(getopt -n "$0" -o hvf: -l help,verbose,file: -- "$@") || exit 1

# 将解析后的参数设为 $1 $2 ...
eval set -- "$PARSED"

while true; do
  case "$1" in
    -h|--help)
      echo "show help"
      shift                 # 从 $@ 移除一个参数
      ;;
    -v|--verbose)
      echo "verbose mode"
      shift                 # 从 $@ 移除一个参数
      ;;
    -f|--file)
      echo "file = $2"
      shift 2               # 从 $@ 移除两个参数
      ;;
    --)
      shift                 # 从 $@ 移除一个参数
      break
      ;;
  esac
done

echo "剩余参数: $@"

#相关命令

命令说明
getopts解析选项参数

#推荐阅读

#手册

更新: 2026/4/1

作者: PlanC

创建: 2026/1/16