← 返回命令列表

Linux command

getopts 命令

文件

涉及管道、覆盖或删除,执行前请先确认路径和参数。

常用示例

Basic option parsing

while getopts "ab:c" opt; do case $opt in a) echo "Option a";; b) echo "Option b with arg: $OPTARG";; c) echo "Option c";; esac; done

Parse options with arguments

getopts "f:o:v" opt

Silent error mode

getopts ":ab:c" opt

Shift processed arguments

shift $((OPTIND - 1))

Handle unknown options

case $opt in \?) echo "Invalid option: -$OPTARG";; esac

说明

getopts is a POSIX shell builtin for parsing short command-line options in scripts. It processes options one at a time, typically used in a while loop with a case statement to handle each option. Options are single characters preceded by a dash (e.g., -a, -b). Options can be combined (-abc). Options requiring arguments can have the argument immediately following (-ffile) or as the next argument (-f file). When all options are processed, getopts returns a non-zero exit status. After parsing, use shift $((OPTIND - 1)) to remove processed options, leaving remaining arguments in $@.

FAQ

What is the getopts command used for?

getopts is a POSIX shell builtin for parsing short command-line options in scripts. It processes options one at a time, typically used in a while loop with a case statement to handle each option. Options are single characters preceded by a dash (e.g., -a, -b). Options can be combined (-abc). Options requiring arguments can have the argument immediately following (-ffile) or as the next argument (-f file). When all options are processed, getopts returns a non-zero exit status. After parsing, use shift $((OPTIND - 1)) to remove processed options, leaving remaining arguments in $@.

How do I run a basic getopts example?

Run `while getopts "ab:c" opt; do case $opt in a) echo "Option a";; b) echo "Option b with arg: $OPTARG";; c) echo "Option c";; esac; done` in a terminal, then adjust file names, paths, flags, or remote targets for your system.

Where can I find more getopts examples?

This page includes 5 examples for getopts, plus related commands for nearby Linux tasks.