1.\" $NetBSD: getopt.1,v 1.17 2009/03/11 13:53:30 joerg Exp $ 2.Dd November 9, 2000 3.Dt GETOPT 1 4.Os 5.Sh NAME 6.Nm getopt 7.Nd parse command options 8.Sh SYNOPSIS 9.Li args=\`getopt optstring $*\` 10.Pp 11.Li set \-\- \`getopt optstring $*\` 12.Sh DESCRIPTION 13.Nm 14is used to break up options in command lines for easy parsing by 15shell procedures, and to check for legal options. 16.Op Optstring 17is a string of recognized option letters (see 18.Xr getopt 3 ) ; 19if a letter is followed by a colon, the option 20is expected to have an argument which may or may not be 21separated from it by white space. 22The special option 23.Dq \-\- 24is used to delimit the end of the options. 25.Nm 26will place 27.Dq \-\- 28in the arguments at the end of the options, 29or recognize it if used explicitly. 30The shell arguments 31.Pq Ev $1 , Ev $2 , ... 32are reset so that each option is 33preceded by a 34.Dq \- 35and in its own shell argument; 36each option argument is also in its own shell argument. 37.Sh EXAMPLES 38The following code fragment shows how one might process the arguments 39for a command that can take the options 40.Op a 41and 42.Op b , 43and the option 44.Op c , 45which requires an argument. 46.Pp 47.Bd -literal -offset indent 48args=\`getopt abc: $*\` 49if [ $? \-ne 0 ]; then 50 echo 'Usage: ...' 51 exit 2 52fi 53set \-\- $args 54while [ $# \-gt 0 ]; do 55 case "$1" in 56 \-a|\-b) 57 flag=$1 58 ;; 59 \-c) 60 carg=$2; shift 61 ;; 62 \-\-) 63 shift; break 64 ;; 65 esac 66 shift 67done 68.Ed 69.Pp 70This code will accept any of the following as equivalent: 71.Pp 72.Bd -literal -offset indent 73cmd \-acarg file file 74cmd \-a \-c arg file file 75cmd \-carg -a file file 76cmd \-a \-carg \-\- file file 77.Ed 78.Pp 79.St -p1003.2 80mandates that the 81.Xr sh 1 82set command return the value of 0 for the exit status. 83Therefore, the exit status of the 84.Nm 85command is lost when 86.Nm 87and the 88.Xr sh 1 89set command are used on the same line. 90The example given is one way to detect errors found by 91.Nm . 92.Sh DIAGNOSTICS 93.Nm 94prints an error message on the standard error output when it 95encounters an option letter not included in 96.Op optstring . 97.Sh SEE ALSO 98.Xr sh 1 , 99.Xr getopt 3 100.Sh HISTORY 101Written by Henry Spencer, working from a Bell Labs manual page. 102Behavior believed identical to the Bell version. 103.Sh BUGS 104Whatever 105.Xr getopt 3 106has. 107.Pp 108Arguments containing white space or embedded shell metacharacters 109generally will not survive intact; this looks easy to fix but isn't. 110.Pp 111The error message for an invalid option is identified as coming 112from 113.Nm 114rather than from the shell procedure containing the invocation 115of 116.Nm ; 117this again is hard to fix. 118.Pp 119The precise best way to use the 120.Ic set 121command to set the arguments without disrupting the value(s) of 122shell options varies from one shell version to another. 123