.\" -*- coding: UTF-8 -*- '\" t .\" Copyright (c) 1993 by Thomas Koenig (ig25@rz.uni-karlsruhe.de) .\" and Copyright 2006-2008, Michael Kerrisk .\" .\" SPDX-License-Identifier: Linux-man-pages-copyleft .\" .\" 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 "15 декабря 2022 г." "Linux man\-pages 6.02" .SH ИМЯ getopt, getopt_long, getopt_long_only, optarg, optind, opterr, optopt \- разбираю параметры командной строки .SH LIBRARY Standard C library (\fIlibc\fP, \fI\-lc\fP) .SH СИНТАКСИС .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 \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 Требования макроса тестирования свойств для glibc (см. \fBfeature_test_macros\fP(7)): .RE .PP \fBgetopt\fP(): .nf _POSIX_C_SOURCE >= 2 || _XOPEN_SOURCE .fi .PP \fBgetopt_long\fP(), \fBgetopt_long_only\fP(): .nf _GNU_SOURCE .fi .SH ОПИСАНИЕ Функция \fBgetopt\fP() разбирает аргументы командной строки. Её аргументы \fIargc\fP и \fIargv\fP являются счётчиком и массивом аргументов, которые передаются функции \fImain\fP() при запуске программы. Элемент \fIargv\fP, начинающийся с «\-» (и не являющийся «\-» или «\-\-»), считается параметром. Символы этого элемента (не считая начального «\-») являются символами параметра. При каждом повторном вызове \fBgetopt\fP() возвращают следующий символ параметра и так для каждого следующего параметра. .PP Переменная \fIoptind\fP — это индекс следующего обрабатываемого элемента \fIargv\fP. Система инициализирует это значение 1. Вызывающий может сбросить его в 1 для перезапуска сканирования того же \fIargv\fP, или при сканировании нового вектора аргументов. .PP Если \fBgetopt\fP() встречает символ другого параметра, она возвращает этот символ, обновляя внешнюю переменную \fIoptind\fP и статическую переменную \fInextchar\fP, так что следующий вызов \fBgetopt\fP() может продолжить проверку с символа следующего параметра или элемента \fIargv\fP. .PP Если символов параметров больше нет, то \fBgetopt\fP() возвращает \-1. При этом \fIoptind\fP станет индексом первого элемента \fIargv\fP, не являющегося параметром. .PP \fIoptstring\fP is a string containing the legitimate option characters. A legitimate option character is any visible one byte \fBascii\fP(7) character (for which \fBisgraph\fP(3) would return nonzero) that is not \(aq\-\(aq, \(aq:\(aq, or \(aq;\(aq. 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 \(aq+\(aq is not the first character of \fIoptstring\fP, it is treated as a normal option. If \fBPOSIXLY_CORRECT\fP behaviour is required in this case \fIoptstring\fP will contain two \(aq+\(aq symbols. 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 При обработке списка параметров \fBgetopt\fP() может определить два типа ошибок: (1) — символ параметра, не заданный в \fIoptstring\fP и (2) — отсутствующий аргумент параметра (т. е., параметра в конце командной строки без ожидаемого аргумента). Эти ошибки обрабатываются и о них сообщается следующем образом: .IP \(bu 3 По умолчанию, \fBgetopt\fP() печатает сообщение об ошибке в стандартный поток ошибок, помещает ошибочный символ параметра в \fIoptopt\fP и возвращает \(aq?\(aq как результат функции. .IP \(bu Если вызывающий присвоил глобальной переменной \fIopterr\fP значение 0, то \fBgetopt\fP() не печатает сообщение об ошибке. Вызывающий может определить, что произошла ошибка, сравнив возвращаемое значение функции с \(aq?\(aq (по умолчанию \fIopterr\fP имеет ненулевое значение). .IP \(bu .\" Если первый символ (после необязательных \(aq+\(aq или \(aq\-\(aq, описанных выше) \fIoptstring\fP — двоеточие (\(aq:\(aq), то \fBgetopt\fP() также не печатает сообщение об ошибке. При этом возвращается \(aq:\(aq вместо \(aq?\(aq, что показывает отсутствие аргумента параметра. Это позволяет вызывающему отличить один тип ошибок от другого. .SS "getopt_long() и getopt_long_only()" Функция \fBgetopt_long\fP() работает так же, как \fBgetopt\fP(), за исключением того, что она воспринимает и длинные параметры, начинающиеся с двух дефисов (если программа принимает только длинные параметры, то значение \fIoptstring\fP должно быть равно пустой строке (""), не NULL). Длинные параметры можно сокращать, если сокращение сохраняет уникальность параметра или полностью совпадает с одним из определённых параметров. Длинный параметр может иметь значение вида \fB\-\-параметр=значение\fP или \fB\-\-параметр значение\fP. .PP Аргумент \fIlongopts\fP является указателем на первый элемент массива структур \fIstruct option\fP, объявленного в \fI\fP следующим образом .PP .in +4n .EX struct option { const char *name; int has_arg; int *flag; int val; }; .EE .in .PP Значения различных полей: .TP \fIимя\fP имя длинного параметра .TP \fIhas_arg\fP может быть: \fBno_argument\fP (или 0), если параметр не требует значения; \fBrequired_argument\fP (или 1), если параметр требует значения; \fBoptional_argument\fP (или 2), если параметр может иметь необязательное значение. .TP \fIflag\fP способ возвращения результатов для длинного параметра. Если \fIflag\fP равен NULL, то \fBgetopt_long\fP() возвращает \fIval\fP (например, вызывающая программа может назначить \fIval\fP эквивалентом символа короткого параметра). В противном случае \fBgetopt_long\fP() возвращает 0, а \fIflag\fP указывает на переменную, устанавливаемое значение которой равно \fIval\fP, если параметр найден; и оставляемую без изменений, если параметр не найден. .TP \fIval\fP значение, которое возвращается или загружается в переменную, на которую указывает \fIflag\fP. .PP Последний элемент массива должен быть заполнен нулями. .PP Если \fIlongindex\fP не равен NULL, то он указывает на переменную, содержащую индекс длинного параметра в соответствии с \fIlongopts\fP. .PP Функция \fBgetopt_long_only\fP() работает так же, как \fBgetopt_long\fP(), но в качестве указателя длинного параметра может служить не только «\-\-», но и «\-». Если параметр, начинающийся с «\-» (не с «\-\-»), не совпадает с длинным параметром, но совпадает с коротким, то он обрабатывается как короткий параметр. .SH "ВОЗВРАЩАЕМОЕ ЗНАЧЕНИЕ" Если параметр найден, то \fBgetopt\fP() возвращает символ параметра. Если все параметры командной строки обработаны, то \fBgetopt\fP() возвращает \-1. Если \fBgetopt\fP() находит символ, которого нет в \fIoptstring\fP, то возвращается «?». Если \fBgetopt\fP() находит символ с отсутствующим аргументом, то возвращаемое значение зависит от первого символа \fIoptstring\fP: если это «:», то возвращается «:», в противном случае возвращается «?». .PP Функции \fBgetopt_long\fP() и \fBgetopt_long_only\fP() также возвращают символ параметра, если распознан короткий параметр. Для длинного параметра они возвращают \fIval\fP, если \fIflag\fP равен NULL, и 0 в противном случае. Возвращаемые ошибки и \-1 имеют то же значение, что и для \fBgetopt\fP(), кроме того, «?» возвращается при двусмысленном толковании параметра. .SH ОКРУЖЕНИЕ .TP \fBPOSIXLY_CORRECT\fP Если установлена эта переменная, то обработка параметров прерывается на первом аргументе, не являющемся параметром. .TP \fB__GNU_nonoption_argv_flags_\fP This variable was used by \fBbash\fP(1) 2.0 to communicate to glibc which arguments are the results of wildcard expansion and so should not be considered as options. This behavior was removed in \fBbash\fP(1) 2.01, but the support remains in glibc. .SH АТРИБУТЫ Описание терминов данного раздела смотрите в \fBattributes\fP(7). .ad l .nh .TS allbox; lb lb lbx l l l. Интерфейс Атрибут Значение T{ \fBgetopt\fP(), \fBgetopt_long\fP(), \fBgetopt_long_only\fP() T} Безвредность в нитях T{ MT\-Unsafe race:getopt env T} .TE .hy .ad .sp 1 .SH СТАНДАРТЫ .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 Использование «+» и «\-» в \fIoptstring\fP является расширением GNU. .IP В некоторых старых реализациях \fBgetopt\fP() объявлялась в \fI\fP. В SUSv1 разрешено её объявлять в \fI\fP или \fI\fP. В POSIX.1\-1996 отмечено, что использование \fI\fP УСТАРЕЛО. В POSIX.1\-2001 не требуется объявлять эту функцию в \fI\fP. .TP \fBgetopt_long\fP() и \fBgetopt_long_only\fP(): Эти функции являются расширениями GNU. .SH ЗАМЕЧАНИЯ В программе, где анализируется несколько векторов параметров, или разбирается один вектор более одного раза и нужно использовать расширения GNU «+» и «\-» в начале \fIoptstring\fP или изменять значение \fBPOSIXLY_CORRECT\fP между разборами, должна повторно инициализировать \fBgetopt\fP() сбрасывая \fIoptind\fP в 0, а не в обычное значение 1 (сброс в 0 вызывает принудительный вызов внутренней процедуры, повторно проверяющей \fBPOSIXLY_CORRECT\fP и расширения GNU в \fIoptstring\fP). .PP Command\-line arguments are parsed in strict order meaning that an option requiring an argument will consume the next argument, regardless of whether that argument is the correctly specified option argument or simply the next option (in the scenario the user mis\-specifies the command line). For example, if \fIoptstring\fP is specified as "1n:" and the user specifies the command line arguments incorrectly as \fIprog\ \-n\ \-1\fP, the \fI\-n\fP option will be given the \fBoptarg\fP value "\-1", and the \fI\-1\fP option will be considered to have not been specified. .SH ПРИМЕРЫ .SS getopt() В приведённом ниже пример программы \fBgetopt\fP() используется два параметра программы: \fI\-n\fP без значения и \fI\-t значение\fP со значением. .PP .\" SRC BEGIN (getopt.c) .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, "Использование: %s [\-t nsecs] [\-n] имя\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, "После параметра требуется значение\en"); exit(EXIT_FAILURE); } printf("параметр = %s\en", argv[optind]); /* остальной код не показан */ exit(EXIT_SUCCESS); } .EE .\" SRC END .SS getopt_long() Приведённый ниже пример программы иллюстрирует использование большинства возможностей \fBgetopt_long\fP(). .PP .\" SRC BEGIN (getopt_long.c) .EX #include #include /* for printf */ #include /* for exit */ 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("параметр %s", long_options[option_index].name); if (optarg) printf(" со значением %s", optarg); printf("\en"); break; case \(aq0\(aq: case \(aq1\(aq: case \(aq2\(aq: if (digit_optind != 0 && digit_optind != this_option_optind) printf("Встречена цифра в двух различных элементах argv.\en"); digit_optind = this_option_optind; printf("параметр %c\en", c); break; case \(aqa\(aq: printf("параметр a\en"); break; case \(aqb\(aq: printf("параметр b\en"); break; case \(aqc\(aq: printf("параметр c со значением «%s»\en", optarg); break; case \(aqd\(aq: printf("параметр d со значением «%s»\en", optarg); break; case \(aq?\(aq: break; default: printf("?? getopt вернула код символа 0%o ??\en", c); } } if (optind < argc) { printf("элементы ARGV не параметры: "); while (optind < argc) printf("%s ", argv[optind++]); printf("\en"); } exit(EXIT_SUCCESS); } .EE .\" SRC END .SH "СМ. ТАКЖЕ" \fBgetopt\fP(1), \fBgetsubopt\fP(3) .PP .SH ПЕРЕВОД Русский перевод этой страницы руководства был сделан Azamat Hackimov , Dmitry Bolkhovskikh , Vladislav , Yuri Kozlov и Иван Павлов . .PP Этот перевод является бесплатной документацией; прочитайте .UR https://www.gnu.org/licenses/gpl-3.0.html Стандартную общественную лицензию GNU версии 3 .UE или более позднюю, чтобы узнать об условиях авторского права. Мы не несем НИКАКОЙ ОТВЕТСТВЕННОСТИ. .PP Если вы обнаружите ошибки в переводе этой страницы руководства, пожалуйста, отправьте электронное письмо на .MT man-pages-ru-talks@lists.sourceforge.net .ME .