Provided by: manpages-fr-dev_4.13-4_all 

NOM
getopt, getopt_long, getopt_long_only, optarg, optind, opterr, optopt - Analyser les options de la ligne
de commande
SYNOPSIS
#include <unistd.h>
int getopt(int argc, char * const argv[],
const char *optstring);
extern char *optarg;
extern int optind, opterr, optopt;
#include <getopt.h>
int getopt_long(int argc, char * const argv[],
const char *optstring,
const struct option *longopts, int *longindex);
int getopt_long_only(int argc, char * const argv[],
const char *optstring,
const struct option *longopts, int *longindex);
Exigences de macros de test de fonctionnalités pour la glibc (consulter feature_test_macros(7)) :
getopt() : _POSIX_C_SOURCE >= 2 || _XOPEN_SOURCE
getopt_long(), getopt_long_only() : _GNU_SOURCE
DESCRIPTION
La fonction getopt() analyse les arguments de la ligne de commande. Ses éléments argc et argv
correspondent aux nombres et à la table d'arguments qui sont transmis à la fonction main() lors du
lancement du programme. Un élément de argv qui commence par « - » (et qui ne soit pas uniquement « -- »
ou « - ») est considéré comme une option. Les caractères à la suite du « - » initial sont les caractères
de l'option. Si getopt() est appelée à plusieurs reprises, elle renverra successivement chaque caractère
de chaque option.
La variable optind est l'indice de l'élément suivant à analyser dans argv. Le système initialise cette
valeur à 1. L'appelant peut le remettre à 1 pour recommencer l'analyse du même argv ou pour analyser un
nouveau tableau de paramètre.
Si getopt() trouve un autre caractère d'option, elle le renvoie, mettant à jour la variable externe
optind et la variable statique nextchar, ainsi l'appel suivant à getopt() peut continuer l'analyse avec
le caractère suivant ou l'élément argv.
S'il n'y a plus de caractères d'option, getopt() renvoie -1. Alors, optind devient l'index du premier
élément de argv qui ne soit pas une option.
optstring est une chaîne contenant l'ensemble des caractères d'option autorisés. Si un de ces caractères
est suivi par un deux-points (« : »), l'option nécessite un argument, donc getopt() placera un pointeur
sur le texte suivant dans le même argv, ou sur le texte de l'élément argv suivant dans optarg. Un double
deux points (« :: ») signifie qu'une option prend un argument optionnel. S'il existe un texte dans le
même élément de argv (c'est-à-dire dans le même mot que l'option elle-même comme « -oarg ») alors il est
renvoyé dans optarg, sinon optarg est défini à zéro. Il s'agit d'une extension GNU. Si optstring contient
W suivi d'un point-virgule, alors -W foo est traité comme l'option longue --foo (l'option -W est réservée
par POSIX.2 pour des extensions spécifique à l'implémentation). Ce comportement, spécifique à la version
GNU, n'est pas disponible avant la bibliothèque glibc 2.
By default, getopt() permutes the contents of argv 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 optstring is '+'
or the environment variable POSIXLY_CORRECT is set, then option processing stops as soon as a nonoption
argument is encountered. If the first character of optstring is '-', then each nonoption argv-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 argv-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.
While processing the option list, getopt() can detect two kinds of errors: (1) an option character that
was not specified in optstring 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:
– By default, getopt() prints an error message on standard error, places the erroneous option character
in optopt, and returns '?' as the function result.
– If the caller has set the global variable opterr to zero, then getopt() does not print an error
message. The caller can determine that there was an error by testing whether the function return value
is '?'. (By default, opterr has a nonzero value.)
– If the first character (following any optional '+' or '-' described above) of optstring is a colon
(':'), then getopt() likewise does not print an error message. In addition, it returns ':' instead of
'?' to indicate a missing option argument. This allows the caller to distinguish the two different
types of errors.
getopt_long() et getopt_long_only()
La fonction getopt_long() fonctionne comme getopt() sauf qu'elle accepte également des noms longs
d'option, commençant par deux tirets (si le programme accepte seulement les options longues, alors
optstring devrait être indiquée avec une chaîne vide « "" » et non avec NULL). Les noms longs d'option
peuvent être abrégés, si l'abréviation est unique, ou si elle correspond exactement à une option définie.
Une option longue peut prendre un argument, de la forme --arg=param ou --arg param.
longopts est un pointeur sur le premier élément d'un tableau de structures struct option déclarées dans
<getopt.h> ainsi :
struct option {
const char *name;
int has_arg;
int *flag;
int val;
};
La signification des différents champs est la suivante :
nom est le nom de l'option longue.
has_arg
vaut : no_argument (ou 0), si l'option ne prend pas d'argument, required_argument (ou 1) si
l'option prend un argument, ou optional_argument (ou 2) si l'option prend un argument optionnel.
flag indique la manière de renvoyer les résultats pour une option longue. Si flag vaut NULL, alors
getopt_long() renvoie val (par exemple, le programme appelant peut remplir val avec le caractère
de l'option courte correspondante). Sinon, getopt_long() renvoie 0, et flag pointe sur une
variable définie à val si l'option est trouvée, mais reste inchangé si l'option est absente.
val est la valeur à renvoyer, ou à charger dans la variable pointée par flag.
Le dernier élément de la table doit être rempli avec des zéros.
Si longindex n'est pas NULL, il pointe sur une variable qui est définie avec l'index de l'option longue
correspondant à longopts.
getopt_long_only() fonctionne comme getopt_long(), mais « - » tout comme « -- » peut indiquer une option
longue. Si une option commençant par « - » (et non « -- ») ne correspond pas à une option longue, mais
correspond à une option courte, elle est analysée en tant qu'option courte.
VALEUR RENVOYÉE
Si une option a été trouvée, alors getopt() renvoie le caractère de l'option. Si toutes les options de la
ligne de commande ont été lues, alors getopt() renvoie -1. Si getopt() rencontre un caractère d'option
qui n'est pas dans optstring, alors « ? » est renvoyé. Si getopt() rencontre une option avec un argument
manquant, alors la valeur renvoyée dépend du premier caractère de optstring : si c'est « : », alors ce
caractère est renvoyé, sinon « ? » est renvoyé.
getopt_long() et getopt_long_only() renvoient également le caractère d'option courte s'ils en trouvent
une. Pour les options longues, ils renvoient val si flag vaut NULL, et 0 sinon. Les erreurs et la fin des
options sont gérées comme avec getopt(), en renvoyant de surcroît « ? » pour une correspondance ambiguë,
ou un paramètre en trop.
ENVIRONNEMENT
POSIXLY_CORRECT
Si cette variable est positionnée, l'analyse s'arrête dès qu'un argument ne constituant pas une
option est rencontré.
_<PID>_GNU_nonoption_argv_flags_
Cette variable est utilisée par bash(1) 2.0 pour communiquer à la glibc les arguments résultant de
l'expansion des caractères génériques, et ils ne doivent pas être considérés comme des options. Ce
comportement a été supprimé de bash(1) version 2.01, mais il est toujours géré par la glibc.
ATTRIBUTS
Pour une explication des termes utilisés dans cette section, consulter attributes(7).
┌──────────────────────────┬──────────────────────┬───────────────────────────┐
│ Interface │ Attribut │ Valeur │
├──────────────────────────┼──────────────────────┼───────────────────────────┤
│ getopt(), getopt_long(), │ Sécurité des threads │ MT-Unsafe race:getopt env │
│ getopt_long_only() │ │ │
└──────────────────────────┴──────────────────────┴───────────────────────────┘
CONFORMITÉ
getopt() :
POSIX.1-2001, POSIX.1-2008, and POSIX.2, provided the environment variable POSIXLY_CORRECT is set.
Otherwise, the elements of argv aren't really const, because these functions permute them.
Nevertheless, const is used in the prototype to be compatible with other systems.
L'utilisation de '+' et '-' dans optstring est une extension GNU.
On some older implementations, getopt() was declared in <stdio.h>. SUSv1 permitted the
declaration to appear in either <unistd.h> or <stdio.h>. POSIX.1-1996 marked the use of <stdio.h>
for this purpose as LEGACY. POSIX.1-2001 does not require the declaration to appear in <stdio.h>.
getopt_long() et getopt_long_only() :
Ces fonctions sont des extensions GNU.
NOTES
Un programme qui analyse plusieurs tableaux de paramètres ou analyse de nouveau le même tableau plusieurs
fois, et qui veut utiliser les extension GNU telles que '+' et '-' au début de optstring, ou changer la
valeur de POSIXLY_CORRECT entre les analyses, doit réinitialiser getopt() en remettant optind à 0, plutôt
que la valeur traditionnelle de 1. La remise à 0 force l'appel d'une routine d'initialisation interne qui
vérifie POSIXLY_CORRECT et vérifie les extensions GNU dans optstring.
EXEMPLES
getopt()
Le programme d'exemple trivial suivant utilise getopt() avec 2 options :-n sans valeur associée et -t val
qui nécessite une valeur.
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
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 'n':
flags = 1;
break;
case 't':
nsecs = atoi(optarg);
tfnd = 1;
break;
default: /* '?' */
fprintf(stderr, "Usage: %s [-t nsecs] [-n] name\n",
argv[0]);
exit(EXIT_FAILURE);
}
}
printf("flags=%d; tfnd=%d; nsecs=%d; optind=%d\n",
flags, tfnd, nsecs, optind);
if (optind >= argc) {
fprintf(stderr, "Expected argument after options\n");
exit(EXIT_FAILURE);
}
printf("name argument = %s\n", argv[optind]);
/* Other code omitted */
exit(EXIT_SUCCESS);
}
getopt_long()
The following example program illustrates the use of getopt_long() with most of its features.
#include <stdio.h> /* for printf */
#include <stdlib.h> /* for exit */
#include <getopt.h>
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, 'c'},
{"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("\n");
break;
case '0':
case '1':
case '2':
if (digit_optind != 0 && digit_optind != this_option_optind)
printf("digits occur in two different argv-elements.\n");
digit_optind = this_option_optind;
printf("option %c\n", c);
break;
case 'a':
printf("option a\n");
break;
case 'b':
printf("option b\n");
break;
case 'c':
printf("option c with value '%s'\n", optarg);
break;
case 'd':
printf("option d with value '%s'\n", optarg);
break;
case '?':
break;
default:
printf("?? getopt returned character code 0%o ??\n", c);
}
}
if (optind < argc) {
printf("non-option ARGV-elements: ");
while (optind < argc)
printf("%s ", argv[optind++]);
printf("\n");
}
exit(EXIT_SUCCESS);
}
VOIR AUSSI
getopt(1), getsubopt(3)
COLOPHON
Cette page fait partie de la publication 5.10 du projet man-pages Linux. Une description du projet et des
instructions pour signaler des anomalies et la dernière version de cette page peuvent être trouvées à
l'adresse https://www.kernel.org/doc/man-pages/.
TRADUCTION
La traduction française de cette page de manuel a été créée par Christophe Blaess
<https://www.blaess.fr/christophe/>, Stéphan Rafin <stephan.rafin@laposte.net>, Thierry Vignaud
<tvignaud@mandriva.com>, François Micaux, Alain Portal <aportal@univ-montp2.fr>, Jean-Philippe Guérard
<fevrier@tigreraye.org>, Jean-Luc Coulon (f5ibh) <jean-luc.coulon@wanadoo.fr>, Julien Cristau
<jcristau@debian.org>, Thomas Huriaux <thomas.huriaux@gmail.com>, Nicolas François
<nicolas.francois@centraliens.net>, Florentin Duneau <fduneau@gmail.com>, Simon Paillard
<simon.paillard@resel.enst-bretagne.fr>, Denis Barbier <barbier@debian.org> et David Prévot
<david@tilapin.org>
Cette traduction est une documentation libre ; veuillez vous reporter à la GNU General Public License
version 3 concernant les conditions de copie et de distribution. Il n'y a aucune RESPONSABILITÉ LÉGALE.
Si vous découvrez un bogue dans la traduction de cette page de manuel, veuillez envoyer un message à
debian-l10n-french@lists.debian.org.
GNU 9 juin 2020 GETOPT(3)