Sponsored Content
Top Forums Shell Programming and Scripting ksh function getopts get leading underscore unless preceded by hyphen Post 302437249 by kchriste on Wednesday 14th of July 2010 12:10:23 PM
Old 07-14-2010
ksh function getopts get leading underscore unless preceded by hyphen

If I call my function with grouped options: "logm -TDIWEFO 'message' ", then only the "T" gets parsed correctly. The subsequent values returned have underscores prefixed to the value: "_D", "_I", etc. If I "logm -T -DIWEFO 'message' ", the "T" and the "D" are OK, but "I" through "O" get the underscores.

Can someone, please, point out what I'm doing wrong.

Here's the function (with debugging "echo"s included):

Code:
function logm
{
echo inside logm
#OPTSTRING=":tTdDiIwWeEfFoO"
#while getopts ${OPTSTRING} opt
while getopts ":tTdDiIwWeEfFoO" opt
        do
echo OPTIND=${OPTIND}
echo OPTARG=${OPTARG}
echo opt=$opt
echo 1=$1
echo 2=$2
echo 3=$3
echo 4=$4
                case ${opt} in
                        t|T)
                          echo log TRACE ${2}
                          log TRACE ${2}
                          ;;
                        d)
                          echo log DEBUG ${2}
                          log DEBUG ${2}
                          ;;
                        D)
                          echo log DEBUG ${2}
                          log DEBUG ${2}
                          ;;
                        i|I)
                          echo log INFO ${2}
                          log INFO ${2}
                          ;;
                        w|W)
                          echo log WARN ${2}
                          log WARN ${2}
                          ;;
                        e|E)
                          echo log ERROR ${2}
                          log ERROR ${2}
                          ;;
                        f|F)
                          echo log FATAL ${2}
                          log FATAL ${2}
                          ;;
                        o|O)
                          echo log OFF ${2}
                          log OFF ${2}
                          ;;
                        *)
                         echo unknown opt $opt
                         ;;
                esac
        done
unset OPTSTRING
unset OPTIND
}

Here's how I call it:

Code:
logm -TDIWEFO "this is the tdiwefo message"

Here're the results:

Code:
inside logm
OPTIND=1
OPTARG=
opt=T
1=-TDIWEFO
2=this is the tdiwefo message
3=
4=
log TRACE this is the tdiwefo message
OPTIND=1
OPTARG=
opt=_D
1=-TDIWEFO
2=this is the tdiwefo message
3=
4=
unknown opt _D
OPTIND=1
OPTARG=
opt=_I
1=-TDIWEFO
2=this is the tdiwefo message
3=
4=
unknown opt _I
OPTIND=1
OPTARG=
opt=_W
1=-TDIWEFO
2=this is the tdiwefo message
3=
4=
unknown opt _W
OPTIND=1
OPTARG=
opt=_E
1=-TDIWEFO
2=this is the tdiwefo message
3=
4=
unknown opt _E
OPTIND=1
OPTARG=
opt=_F
1=-TDIWEFO
2=this is the tdiwefo message
3=
4=
unknown opt _F
OPTIND=2
OPTARG=
opt=_O
1=-TDIWEFO
2=this is the tdiwefo message
3=
4=
unknown opt _O

 

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

ksh: can you use getopts in a function?

I wrote a script that uses getopts and it works fine. However, I would like to put the function in that script in a startup file (.kshrc or .profile). I took the "main" portion of the script and made it a function in the startup script. I source the startup script but it doesn't seem to parse... (4 Replies)
Discussion started by: lyonsd
4 Replies

2. Shell Programming and Scripting

egrep string except when preceded by underscore

having trouble with this seemingly simple taks.. :mad: Test data: we want to keep lines 2,3 & 4 -- want to exclude when ${.*schema} is preceded with an underscore; Valid {.*schema} should always be preceded spaces or be found at the beginning of a line. egrep... (5 Replies)
Discussion started by: danmauer
5 Replies

3. Shell Programming and Scripting

Using of gsub function in AWK to replace space by underscore

I must design a UNIX script to monitor files whose size is over a threshold of 5 MB in a specific UNIX directory I meet a problem during the for loop in my script. Some file names contain spaces. ls -lrt | awk '$5>=5000000 && length($8)==5 {gsub(/ /,"_",$9); print};' -rw-r--r-- 1 was61 ... (2 Replies)
Discussion started by: Scofield38
2 Replies

4. Shell Programming and Scripting

Problem to initialize ksh array when first element includes hyphen

Hi I'm trying to create an array with variable including hyphen but ksh refuses the first element set -A allArgs set +A allArgs ${allArgs} -all set +A allArgs ${allArgs} -date set +A allArgs ${allArgs} test ./test.ksh: -all: bad option(s) It happens only when first element is like... (4 Replies)
Discussion started by: gdan2000
4 Replies

5. Shell Programming and Scripting

getopts function in Perl

Hi All I have searches getopts function in Perl a lot, but yet i didn't cleared with it. First I want to know what is the meaning of getopts('t:c:', \%options); and please explain getopts function in an easy way.. (4 Replies)
Discussion started by: parthmittal2007
4 Replies

6. Shell Programming and Scripting

sorting file names with hyphen and underscore

Hi, I have two types of file names filename1_12345 or filename1-12345 at the same time I have second type filename2-12345 in a txt file. I am trying to write awk script that will sort these names with below pattern ALL file names like filename1_12345 and filename1-12345 will go to... (1 Reply)
Discussion started by: rider29
1 Replies

7. Shell Programming and Scripting

Help on getopts in ksh

I am trying to make a Shell Script in KSH on Linux box and Solaris box which takes few arguments... with long options using getopts (not getopt). I have my sample code... at the end I will say my requirement... Please help me folks... $ cat dummy #!/bin/bash # Argument = -t test -r server... (6 Replies)
Discussion started by: explorer007
6 Replies

8. Shell Programming and Scripting

Awk, function of underscore char.

Hello Friends, I would appreciate so much if you could explain how the underscores works at the following code? Sorry if it sounds a bit novice question. awk -F',' 'NR==FNR{_=1;next}!_{print}' exclude infile KR, Eagle (6 Replies)
Discussion started by: EAGL€
6 Replies

9. UNIX for Dummies Questions & Answers

Removing directory with leading hyphen from root directory

I know that this basic question has been asked many times and solutions all over the internet, but none of the are working for me. I have a directory in the root directory, named "-p". # ls -l / total 198 <snip> drwxr-xr-x 4 root root 4096 Dec 3 14:18 opt drwxr-xr-x 2 root ... (2 Replies)
Discussion started by: edstevens
2 Replies

10. UNIX for Beginners Questions & Answers

Deleting directory with leading hyphen in name

I asked this question last month in Stack Exchange (linux - delete directory with leading hyphen - Server Fault) and none of the answers supplied worked. I have somehow created a directory with a leading hyphen and cannot get rid of it. # ls -li | grep p 2621441 drwxr-xr-x. 2 root root... (4 Replies)
Discussion started by: edstevens
4 Replies
getopts(1)							   User Commands							getopts(1)

NAME
getopts - parse utility options SYNOPSIS
/usr/bin/getopts optstring name [ arg...] sh getopts optstring name [argument...] ksh getopts optstring name [arg...] DESCRIPTION
/usr/bin/getopts The getopts utility can be used to retrieve options and option-arguments from a list of parameters. Each time it is invoked, the getopts utility places the value of the next option in the shell variable specified by the name operand and the index of the next argument to be processed in the shell variable OPTIND. Whenever the shell is invoked, OPTIND is initialized to 1. When the option requires an option-argument, the getopts utility places it in the shell variable OPTARG. If no option was found, or if the option that was found does not have an option-argument, OPTARG is unset. If an option character not contained in the optstring operand is found where an option character is expected, the shell variable specified by name is set to the question-mark ( ? ) character. In this case, if the first character in optstring is a colon (:, the shell variable OPTARG is set to the option character found, but no output is written to standard error; otherwise, the shell variable OPTARG is unset and a diagnostic message is written to standard error. This condition is considered to be an error detected in the way arguments were presented to the invoking application, but is not an error in getopts processing. If an option-argument is missing: o If the first character of optstring is a colon, the shell variable specified by name is set to the colon character and the shell vari- able OPTARG is set to the option character found. o Otherwise, the shell variable specified by name is set to the question-mark character (?), the shell variable OPTARG is unset, and a diagnostic message is written to standard error. This condition is considered to be an error detected in the way arguments were pre- sented to the invoking application, but is not an error in getopts processing; a diagnostic message is written as stated, but the exit status is zero. When the end of options is encountered, the getopts utility exits with a return value greater than zero; the shell variable OPTIND is set to the index of the first non-option-argument, where the first -- argument is considered to be an option-argument if there are no other non-option-arguments appearing before it, or the value $# + 1 if there are no non-option-arguments; the name variable is set to the ques- tion-mark character. Any of the following identifies the end of options: the special option --, finding an argument that does not begin with a -, or encountering an error. The shell variables OPTIND and OPTARG are local to the caller of getopts and are not exported by default. The shell variable specified by the name operand, OPTIND and OPTARG affect the current shell execution environment. If the application sets OPTIND to the value 1, a new set of parameters can be used: either the current positional parameters or new arg values. Any other attempt to invoke getopts multiple times in a single shell execution environment with parameters (positional parameters or arg operands) that are not the same in all invocations, or with an OPTIND value modified to be a value other than 1, produces unspeci- fied results. sh getopts is a built-in Bourne shell command used to parse positional parameters and to check for valid options. See sh(1). It supports all applicable rules of the command syntax standard (see Rules 3-10, intro(1)). It should be used in place of the getopt command. optstring must contain the option letters the command using getopts recognizes. If a letter is followed by a colon, the option is expected to have an argument, or group of arguments, which must be separated from it by white space. Each time it is invoked, getopts places the next option in the shell variable name and the index of the next argument to be processed in the shell variable OPTIND. Whenever the shell or a shell script is invoked, OPTIND is initialized to 1. When an option requires an option-argument, getopts places it in the shell variable OPTARG. If an illegal option is encountered, ? is placed in name. When the end of options is encountered, getopts exits with a non-zero exit status. The special option - can be used to delimit the end of the options. By default, getopts parses the positional parameters. If extra arguments (argument ...) are given on the getopts command line, getopts parses them instead. /usr/lib/getoptcvt reads the shell script in filename, converts it to use getopts instead of getopt, and writes the results on the standard output. So that all new commands adhere to the command syntax standard described in intro(1), they should use getopts or getopt to parse positional parameters and check for options that are valid for that command. getopts prints an error message on the standard error when it encounters an option letter not included in optstring. Although the following command syntax rule (see intro(1)) relaxations are permitted under the current implementation, they should not be used because they can not be supported in future releases of the system. As in the EXAMPLES section below, -a and -b are options, and the option -o requires an option-argument. The following example violates Rule 5: options with option-arguments must not be grouped with other options: example% cmd -aboxxx filename The following example violates Rule 6: there must be white space after an option that takes an option-argument: example% cmd -ab oxxx filename Changing the value of the shell variable OPTIND or parsing different sets of arguments can lead to unexpected results. ksh Checks arg for legal options. If arg is omitted, the positional parameters are used. An option argument begins with a + or a -. An option not beginning with + or - or the argument - ends the options. optstring contains the letters that getopts recognizes. If a letter is fol- lowed by a :, that option is expected to have an argument. The options can be separated from the argument by blanks. getopts places the next option letter it finds inside variable name each time it is invoked with a + prepended when arg begins with a +. The index of the next arg is stored in OPTIND. The option argument, if any, gets stored in OPTARG. A leading : in optstring causes getopts to store the letter of an invalid option in OPTARG, and to set name to ? for an unknown option and to : when a required option is missing. Otherwise, getopts prints an error message. The exit status is non-zero when there are no more options. getopts supports both traditional single-character short options and long options defined by Sun's Command Line Interface Paradigm (CLIP). Each long option is an alias for a short option and is specified in parentheses following its equivalent short option. For example, you can specify the long option file as an alias for the short option f using the following script line: getopts "f(file)" opt Precede long options on the command line with -- or ++. In the example above, --file on the command line would be the equivalent of -f, and ++file on the command line would be the equivalent of +f. Each short option can have multiple long option equivalents, although this is in violation of the CLIP specification and should be used with caution. You must enclose each long option equivalent parentheses, as follows: getopts "f:(file)(input-file)o:(output-file)" In the above example, both --file and --input-file are the equivalent of -f, and --output-file is the equivalent of -o. The variable name is always set to a short option. When a long option is specified on the command line, name is set to the short-option equivalent. For a further discussion of the Korn shell's getopts built-in command, see the previous discussion in the Bourne shell (sh) section of this manpage. OPERANDS
The following operands are supported: optstring A string containing the option characters recognised by the utility invoking getopts. If a character is followed by a colon, the option is expected to have an argument, which should be supplied as a separate argument. Applications should specify an option character and its option-argument as separate arguments, but getopts interprets the characters following an option character requiring arguments as an argument whether or not this is done. An explicit null option-argument need not be recognised if it is not supplied as a separate argument when getopts is invoked; see getopt(3C). The characters question-mark (?) and colon (:) must not be used as option characters by an application. The use of other option characters that are not alphanumeric produces unspecified results. If the option-argument is not supplied as a separate argument from the option character, the value in OPTARG is stripped of the option character and the -. The first character in optstring determines how getopts behaves if an option character is not known or an option-argument is missing. name The name of a shell variable that is set by the getopts utility to the option character that was found. The getopts utility by default parses positional parameters passed to the invoking shell procedure. If args are given, they are parsed instead of the positional parameters. USAGE
Since getopts affects the current shell execution environment, it is generally provided as a shell regular built-in. If it is called in a subshell or separate utility execution environment, such as one of the following: (getopts abc value "$@") nohup getopts ... find . -exec getopts ... ; it does not affect the shell variables in the caller's environment. Notice that shell functions share OPTIND with the calling shell even though the positional parameters are changed. Functions that want to use getopts to parse their arguments usually want to save the value of OPTIND on entry and restore it before returning. However, there are cases when a function wants to change OPTIND for the calling shell. EXAMPLES
Example 1: Parsing and Displaying Arguments The following example script parses and displays its arguments: aflag= bflag= while getopts ab: name do case $name in a) aflag=1;; b) bflag=1 bval="$OPTARG";; ?) printf "Usage: %s: [-a] [-b value] args " $0 exit 2;; esac done if [ ! -z "$aflag" ]; then printf "Option -a specified " fi if [ ! -z "$bflag" ]; then printf 'Option -b "%s" specified ' "$bval" fi shift $(($OPTIND - 1)) printf "Remaining arguments are: %s " "$*" Example 2: Processing Arguments for a Command with Options The following fragment of a shell program processes the arguments for a command that can take the options -a or -b. It also processes the option -o, which requires an option-argument: while getopts abo: c do case $c in a | b) FLAG=$c;; o) OARG=$OPTARG;; ?) echo $USAGE exit 2;; esac done shift `expr $OPTIND - 1` Example 3: Equivalent Code Expressions This code example accepts any of the following as equivalent: cmd -a -b -o "xxx z yy" filename cmd -a -b -o "xxx z yy" -- filename cmd -ab -o xxx,z,yy filename cmd -ab -o "xxx z yy" filename cmd -o xxx,z,yy -b -a filename ENVIRONMENT VARIABLES
See environ(5) for descriptions of the following environment variables that affect the execution of getopts: LANG, LC_ALL, LC_CTYPE, LC_MESSAGES, and NLSPATH. OPTIND This variable is used by getopts as the index of the next argument to be processed. OPTARG This variable is used by getopts to store the argument if an option is using arguments. EXIT STATUS
The following exit values are returned: 0 An option, specified or unspecified by optstring, was found. >0 The end of options was encountered or an error occurred. ATTRIBUTES
See attributes(5) for descriptions of the following attributes: +-----------------------------+-----------------------------+ | ATTRIBUTE TYPE | ATTRIBUTE VALUE | +-----------------------------+-----------------------------+ |Availability |SUNWcsu | +-----------------------------+-----------------------------+ |Interface Stability |Standard | +-----------------------------+-----------------------------+ SEE ALSO
intro(1), getoptcvt(1), ksh(1), sh(1), getopt(3C), attributes(5), environ(5), standards(5) DIAGNOSTICS
Whenever an error is detected and the first character in the optstring operand is not a colon (:), a diagnostic message is written to stan- dard error with the following information in an unspecified format: o The invoking program name is identified in the message. The invoking program name is the value of the shell special parameter 0 at the time the getopts utility is invoked. A name equivalent to basename "$0" can be used. o If an option is found that was not specified in optstring, this error is identified and the invalid option character is identified in the message. o If an option requiring an option-argument is found, but an option-argument is not found, this error is identified and the invalid option character is identified in the message. SunOS 5.10 21 Jul 2004 getopts(1)
All times are GMT -4. The time now is 09:01 PM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy