.\" -*- coding: UTF-8 -*- .\" Copyright (c) 1993 by Thomas Koenig (ig25@rz.uni-karlsruhe.de) .\" and Copyright 2006-2008, Michael Kerrisk .\" .\" %%%LICENSE_START(VERBATIM) .\" Permission is granted to make and distribute verbatim copies of this .\" manual provided the copyright notice and this permission notice are .\" preserved on all copies. .\" .\" Permission is granted to copy and distribute modified versions of this .\" manual under the conditions for verbatim copying, provided that the .\" entire resulting derived work is distributed under the terms of a .\" permission notice identical to this one. .\" .\" Since the Linux kernel and libraries are constantly changing, this .\" manual page may be incorrect or out-of-date. The author(s) assume no .\" responsibility for errors or omissions, or for damages resulting from .\" the use of the information contained herein. The author(s) may not .\" have taken the same level of care in the production of this manual, .\" which is licensed free of charge, as they might when working .\" professionally. .\" .\" Formatted or processed versions of this manual, if unaccompanied by .\" the source, must acknowledge the copyright and authors of this work. .\" %%%LICENSE_END .\" .\" Modified Sat Jul 24 19:27:50 1993 by Rik Faith (faith@cs.unc.edu) .\" Modified Mon Aug 30 22:02:34 1995 by Jim Van Zandt .\" longindex is a pointer, has_arg can take 3 values, using consistent .\" names for optstring and longindex, "\n" in formats fixed. Documenting .\" opterr and getopt_long_only. Clarified explanations (borrowing heavily .\" from the source code). .\" Modified 8 May 1998 by Joseph S. Myers (jsm28@cam.ac.uk) .\" Modified 990715, aeb: changed `EOF' into `-1' since that is what POSIX .\" says; moreover, EOF is not defined in . .\" Modified 2002-02-16, joey: added information about nonexistent .\" option character and colon as first option character .\" Modified 2004-07-28, Michael Kerrisk .\" Added text to explain how to order both '[-+]' and ':' at .\" the start of optstring .\" Modified 2006-12-15, mtk, Added getopt() example program. .\" .\"******************************************************************* .\" .\" This file was generated with po4a. Translate the source file. .\" .\"******************************************************************* .TH GETOPT 3 "9 Junio 2020" GNU "Manual del Programador de Linux" .SH NOMBRE getopt, getopt_long, getopt_long_only, optarg, optind, opterr, optopt \- Parse command\-line options .SH SINOPSIS .nf \fB#include \fP .PP \fBint getopt(int \fP\fIargc\fP\fB, char * const \fP\fIargv[]\fP\fB,\fP \fB const char *\fP\fIoptstring\fP\fB);\fP .PP \fBextern char *\fP\fIoptarg\fP\fB;\fP \fBextern int \fP\fIoptind\fP\fB, \fP\fIopterr\fP\fB, \fP\fIoptopt\fP\fB;\fP .PP \fB#include \fP .PP \fBint getopt_long(int \fP\fIargc\fP\fB, char * const \fP\fIargv[]\fP\fB,\fP \fB const char *\fP\fIoptstring\fP\fB,\fP \fB const struct option *\fP\fIlongopts\fP\fB, int *\fP\fIlongindex\fP\fB);\fP .PP \fBint getopt_long_only(int \fP\fIargc\fP\fB, char * const \fP\fIargv[]\fP\fB,\fP \fB const char *\fP\fIoptstring\fP\fB,\fP \fB const struct option *\fP\fIlongopts\fP\fB, int *\fP\fIlongindex\fP\fB);\fP .fi .PP .RS -4 Requisitos de Macros de Prueba de Características para glibc (véase \fBfeature_test_macros\fP(7)): .ad l .RE .PP \fBgetopt\fP(): _POSIX_C_SOURCE\ >=\ 2 || _XOPEN_SOURCE .br \fBgetopt_long\fP(), \fBgetopt_long_only\fP(): _GNU_SOURCE .ad b .SH DESCRIPCIÓN La función \fBgetopt\fP() analiza los argumentos de la línea de órdenes. Sus argumentos \fIargc\fP y \fIargv\fP son el número y el vector de argumentos como los pasados a la función \fImain\fP() cuando se ejecuta el programa. Un elemento de \fIargv\fP que comience con \(aq\-\(aq (y que no sea exactamente "\-" ni "\-\-") es un elemento de opción. Los caracteres de este elemento (aparte del \(aq\-\(aq inicial) son caracteres de opción. Si \fBgetopt\fP() se llama repetidamente, devuelve sucesivamente cada uno de los caracteres de opción de cada uno de los elementos de opción. .PP The variable \fIoptind\fP is the index of the next element to be processed in \fIargv\fP. The system initializes this value to 1. The caller can reset it to 1 to restart scanning of the same \fIargv\fP, or when scanning a new argument vector. .PP Si \fBgetopt\fP() encuentra otro carácter de opción, lo devuelve, actualizando la variable externa \fIoptind\fP y una variable estática \fInextchar\fP de forma que la siguiente llamada a \fBgetopt\fP() pueda seguir la búsqueda en el siguiente carácter de opción o elemento de \fIargv\fP. .PP Si no hay más caracteres de opción, \fBgetopt\fP() devuelve \-1. Entonces \fIoptind\fP es el índice en \fIargv\fP del primer elemento de \fIargv\fP que no es una opción. .PP \fIoptstring\fP is a string containing the legitimate option characters. If such a character is followed by a colon, the option requires an argument, so \fBgetopt\fP() places a pointer to the following text in the same \fIargv\fP\-element, or the text of the following \fIargv\fP\-element, in \fIoptarg\fP. Two colons mean an option takes an optional arg; if there is text in the current \fIargv\fP\-element (i.e., in the same word as the option name itself, for example, "\-oarg"), then it is returned in \fIoptarg\fP, otherwise \fIoptarg\fP is set to zero. This is a GNU extension. If \fIoptstring\fP contains \fBW\fP followed by a semicolon, then \fB\-W foo\fP is treated as the long option \fB\-\-foo\fP. (The \fB\-W\fP option is reserved by POSIX.2 for implementation extensions.) This behavior is a GNU extension, not available with libraries before glibc 2. .PP By default, \fBgetopt\fP() permutes the contents of \fIargv\fP as it scans, so that eventually all the nonoptions are at the end. Two other scanning modes are also implemented. If the first character of \fIoptstring\fP is \(aq+\(aq or the environment variable \fBPOSIXLY_CORRECT\fP is set, then option processing stops as soon as a nonoption argument is encountered. If the first character of \fIoptstring\fP is \(aq\-\(aq, then each nonoption \fIargv\fP\-element is handled as if it were the argument of an option with character code 1. (This is used by programs that were written to expect options and other \fIargv\fP\-elements in any order and that care about the ordering of the two.) The special argument "\-\-" forces an end of option\-scanning regardless of the scanning mode. .PP While processing the option list, \fBgetopt\fP() can detect two kinds of errors: (1) an option character that was not specified in \fIoptstring\fP and (2) a missing option argument (i.e., an option at the end of the command line without an expected argument). Such errors are handled and reported as follows: .IP * 3 By default, \fBgetopt\fP() prints an error message on standard error, places the erroneous option character in \fIoptopt\fP, and returns \(aq?\(aq as the function result. .IP * If the caller has set the global variable \fIopterr\fP to zero, then \fBgetopt\fP() does not print an error message. The caller can determine that there was an error by testing whether the function return value is \(aq?\(aq. (By default, \fIopterr\fP has a nonzero value.) .IP * .\" If the first character (following any optional \(aq+\(aq or \(aq\-\(aq described above) of \fIoptstring\fP is a colon (\(aq:\(aq), then \fBgetopt\fP() likewise does not print an error message. In addition, it returns \(aq:\(aq instead of \(aq?\(aq to indicate a missing option argument. This allows the caller to distinguish the two different types of errors. .SS "getopt_long() y getopt_long_only()" The \fBgetopt_long\fP() function works like \fBgetopt\fP() except that it also accepts long options, started with two dashes. (If the program accepts only long options, then \fIoptstring\fP should be specified as an empty string (""), not NULL.) Long option names may be abbreviated if the abbreviation is unique or is an exact match for some defined option. A long option may take a parameter, of the form \fB\-\-arg=param\fP or \fB\-\-arg param\fP. .PP \fIlongopts\fP es un puntero al primer elemento de un vector de \fIstruct option\fP declarado en \fI\fP como .PP .in +4n .EX struct option { const char *name; int has_arg; int *flag; int val; }; .EE .in .PP Los significados de los diferentes campos son: .TP \fInombre\fP es el nombre de la opción larga. .TP \fIhas_arg\fP es: \fBno_argument\fP (ó 0) si la opción no toma un argumento; \fBrequired_argument\fP (ó 1) si la opción requiere un argumento; u \fBoptional_argument\fP (ó 2) si la opción toma un argumento opcional. .TP \fIflag\fP especifica cómo se devuelven los resultados para una opción larga. Si \fIflag\fP es NULL, entonces \fBgetopt_long\fP() devuelve \fIval\fP. (Por ejemplo, el programa puede poner \fIval\fP como el carácter de opción corta equivalente.) De otro modo, \fBgetopt_long\fP() devuelve 0, y \fIflag\fP apunta a una variable que se pone a \fIval\fP si la opción se encuentra, pero que se deja intacta si la opción no se encuentra. .TP \fIval\fP es el valor a devolver, o a cargar en la variable apuntada por \fIflag\fP. .PP El último elemento del vector tiene que ser llenado con ceros. .PP Si \fIlongindex\fP no es NULL, apunta a una variable que toma el valor del índice de la opción larga relativa a \fIlongopts\fP. .PP \fBgetopt_long_only\fP() es como \fBgetopt_long()\fP, pero tanto \(aq\-\(aq como "\-\-" pueden indicar una opción larga. Si una opción que empiece por \(aq\-\(aq (no "\-\-") no concordara con una opción larga, pero sí con una corta, se consideraría como tal. .SH "VALOR DEVUELTO" If an option was successfully found, then \fBgetopt\fP() returns the option character. If all command\-line options have been parsed, then \fBgetopt\fP() returns \-1. If \fBgetopt\fP() encounters an option character that was not in \fIoptstring\fP, then \(aq?\(aq is returned. If \fBgetopt\fP() encounters an option with a missing argument, then the return value depends on the first character in \fIoptstring\fP: if it is \(aq:\(aq, then \(aq:\(aq is returned; otherwise \(aq?\(aq is returned. .PP \fBgetopt_long\fP() y \fBgetopt_long_only\fP() también devuelven el carácter de la opción cuendo se reconoce una corta. Para una opción larga, devuelven \fIval\fP si \fIflag\fP es NULL, y 0 en otra circunstancia. Las devoluciones de error y \-1 son las mismas que para \fBgetopt\fP(), más \(aq?\(aq indicando una concordancia ambigua o un parámetro extraño. .SH ENTORNO .TP \fBPOSIXLY_CORRECT\fP Si está definida, entonces el procesamiento de las opciones se para tan pronto como se encuentre un argumento que no sea una opción. .TP \fB__GNU_nonoption_argv_flags_\fP Esta variable era utilizada por \fBbash\fP(1) 2.0 para comunicar a glibc qué argumentos eran el resultado de la expansión de comodines y, por tanto, no debían considerarse como opciones. Este comportamiento se eliminó en la versión 2.01 de \fBbash\fP(1) pero el soporte permanece en glibc. .SH ATRIBUTOS Para obtener una explicación de los términos usados en esta sección, véase \fBattributes\fP(7). .TS allbox; lbw24 lb lb l l l. Interfaz Atributo Valor T{ \fBgetopt\fP(), \fBgetopt_long\fP(), \fBgetopt_long_only\fP() T} Seguridad del hilo MT\-Unsafe race:getopt env .TE .SH "CONFORME A" .TP \fBgetopt\fP(): POSIX.1\-2001, POSIX.1\-2008, and POSIX.2, provided the environment variable \fBPOSIXLY_CORRECT\fP is set. Otherwise, the elements of \fIargv\fP aren't really \fIconst\fP, because these functions permute them. Nevertheless, \fIconst\fP is used in the prototype to be compatible with other systems. .IP The use of \(aq+\(aq and \(aq\-\(aq in \fIoptstring\fP is a GNU extension. .IP On some older implementations, \fBgetopt\fP() was declared in \fI\fP. SUSv1 permitted the declaration to appear in either \fI\fP or \fI\fP. POSIX.1\-1996 marked the use of \fI\fP for this purpose as LEGACY. POSIX.1\-2001 does not require the declaration to appear in \fI\fP. .TP \fBgetopt_long\fP() y \fBgetopt_long_only\fP(): Estas funciones son extensiones de GNU. .SH NOTAS A program that scans multiple argument vectors, or rescans the same vector more than once, and wants to make use of GNU extensions such as \(aq+\(aq and \(aq\-\(aq at the start of \fIoptstring\fP, or changes the value of \fBPOSIXLY_CORRECT\fP between scans, must reinitialize \fBgetopt\fP() by resetting \fIoptind\fP to 0, rather than the traditional value of 1. (Resetting to 0 forces the invocation of an internal initialization routine that rechecks \fBPOSIXLY_CORRECT\fP and checks for GNU extensions in \fIoptstring\fP.) .SH EJEMPLOS .SS getopt() The following trivial example program uses \fBgetopt\fP() to handle two program options: \fI\-n\fP, with no associated value; and \fI\-t val\fP, which expects an associated value. .PP .EX #include #include #include int main(int argc, char *argv[]) { int flags, opt; int nsecs, tfnd; nsecs = 0; tfnd = 0; flags = 0; while ((opt = getopt(argc, argv, "nt:")) != \-1) { switch (opt) { case \(aqn\(aq: flags = 1; break; case \(aqt\(aq: nsecs = atoi(optarg); tfnd = 1; break; default: /* \(aq?\(aq */ fprintf(stderr, "Usage: %s [\-t nsecs] [\-n] name\en", argv[0]); exit(EXIT_FAILURE); } } printf("flags=%d; tfnd=%d; nsecs=%d; optind=%d\en", flags, tfnd, nsecs, optind); if (optind >= argc) { fprintf(stderr, "Expected argument after options\en"); exit(EXIT_FAILURE); } printf("name argument = %s\en", argv[optind]); /* Other code omitted */ exit(EXIT_SUCCESS); } .EE .SS getopt_long() El siguiente programa de ejemplo ilustra el empleo de \fBgetopt_long\fP() con la mayoría de sus características. .PP .EX #include /* para printf */ #include /* para exit */ #include int main(int argc, char **argv) { int c; int digit_optind = 0; while (1) { int this_option_optind = optind ? optind : 1; int option_index = 0; static struct option long_options[] = { {"add", required_argument, 0, 0 }, {"append", no_argument, 0, 0 }, {"delete", required_argument, 0, 0 }, {"verbose", no_argument, 0, 0 }, {"create", required_argument, 0, \(aqc\(aq}, {"file", required_argument, 0, 0 }, {0, 0, 0, 0 } }; c = getopt_long(argc, argv, "abc:d:012", long_options, &option_index); if (c == \-1) break; switch (c) { case 0: printf("option %s", long_options[option_index].name); if (optarg) printf(" with arg %s", optarg); printf("\en"); break; case \(aq0\(aq: case \(aq1\(aq: case \(aq2\(aq: if (digit_optind != 0 && digit_optind != this_option_optind) printf("digits occur in two different argv\-elements.\en"); digit_optind = this_option_optind; printf("option %c\en", c); break; case \(aqa\(aq: printf("option a\en"); break; case \(aqb\(aq: printf("option b\en"); break; case \(aqc\(aq: printf("option c with value \(aq%s\(aq\en", optarg); break; case \(aqd\(aq: printf("option d with value \(aq%s\(aq\en", optarg); break; case \(aq?\(aq: break; default: printf("?? getopt returned character code 0%o ??\en", c); } } if (optind < argc) { printf("non\-option ARGV\-elements: "); while (optind < argc) printf("%s ", argv[optind++]); printf("\en"); } exit(EXIT_SUCCESS); } .EE .SH "VÉASE TAMBIÉN" \fBgetopt\fP(1), \fBgetsubopt\fP(3) .SH COLOFÓN Esta página es parte de la versión 5.10 del proyecto Linux \fIman\-pages\fP. Puede encontrar una descripción del proyecto, información sobre cómo informar errores y la última versión de esta página en \%https://www.kernel.org/doc/man\-pages/. .PP .SH TRADUCCIÓN La traducción al español de esta página del manual fue creada por Gerardo Aburruzaga García , Juan Piernas y Miguel Pérez Ibars . .PP Esta traducción es documentación libre; lea la .UR https://www.gnu.org/licenses/gpl-3.0.html GNU General Public License Version 3 .UE o posterior con respecto a las condiciones de copyright. No existe NINGUNA RESPONSABILIDAD. .PP Si encuentra algún error en la traducción de esta página del manual, envíe un correo electrónico a .MT debian-l10n-spanish@lists.debian.org .ME .