sh.1: extend the section about getopts

Provide more details about the influence of optargs' first character
on the shell's behavior in regard to invalid arguments. Also do some
minor word-smithing.

Original submission by rea@

Differential Revision:	https://reviews.freebsd.org/D49106
This commit is contained in:
Piotr Pawel Stefaniak
2025-02-22 16:57:05 +01:00
parent 6b33d9dc46
commit 2980318b27
+46 -14
View File
@@ -31,7 +31,7 @@
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
.Dd January 10, 2025
.Dd February 27, 2025
.Dt SH 1
.Os
.Sh NAME
@@ -2356,29 +2356,61 @@ Move the specified
.Ar job
or the current job to the foreground.
.It Ic getopts Ar optstring var
The POSIX
.Ic getopts
command.
The
.Ic getopts
command deprecates the older
.Xr getopt 1
command.
The first argument should be a series of letters, each possibly
Parse command-line options and arguments.
The first argument
.Va optstring
should be a series of letters, each possibly
followed by a colon which indicates that the option takes an argument.
The specified variable is set to the parsed option.
The specified variable
.Va var
is set to the parsed option.
The index of
the next argument is placed into the shell variable
.Va OPTIND .
If an option takes an argument, it is placed into the shell variable
.Va OPTARG .
If an invalid option is encountered,
.Pp
If the found character
is not specified by
.Va optstring
or if it is missing a required argument,
the option is considered invalid and:
.Bl -offset indent
.It
If the first character of
.Va optstring
is not a colon then
.Va OPTARG
is unset,
.Ar var
is set to
.Ql \&? .
It returns a false value (1) when it encounters the end of the options.
.Ql \&?
and a diagnostic message is written to stderr.
.It
If the first character of
.Va optstring
is a colon then
.Va OPTARG
is set to the the option character found,
.Ar var
is set to
.Ql \&:
when a required argument is missing or to
.Ql \&?
when the option was not specified by
.Va optstring ,
and no diagnostic message is written to stderr.
.El
.Pp
.Ic getopts
returns a false value (1) when it encounters the end of the options.
A new set of arguments may be parsed by assigning
.Li OPTIND=1 .
The POSIX
.Ic getopts
command deprecates the older
.Xr getopt 1
command.
.It Ic hash Oo Fl rv Oc Op Ar command ...
The shell maintains a hash table which remembers the locations of commands.
With no arguments whatsoever, the