Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

getopts 3

Status
Not open for further replies.

pavNell

Technical User
Sep 27, 2002
178
US
a question about getopts command...

suppose I have the following inside my script..

while getopts :x:y: argument
do
case $argument in
x) var1=$OPTARG;;
y) var2=$OPTARG;;
:) echo "No argument given";;
esac
done


in my script, option x is required, no problem. But
option y is not. How do I test to see if option y
was indeed entered on the command line and if not, set some other value to var2.
Thanks.
 
: ${var2:-MyDefaultValue} vlad
+---------------------------+
|#include<disclaimer.h> |
+---------------------------+
 
Hi:

Vlad's solution works well for the Korn shell (and probably Bash). If you're using the bourne shell, you can use:

# test if string var2 is zero length
[ -z &quot;$var2&quot; ]
var2=&quot;defaultvalue&quot;

If you're test command doesn't support -z, you'll have to kludge something like this:

if [ x&quot;$var2&quot; = x ] ;then
var2=&quot;defaultvalue&quot;
fi

Regards,

Ed
 
Hey, thanks!! As a matter of fact I am using korn shell...
so, if I needed MyDefaultValue to be the output of a command, say, `date +%m%d%y` then my parameter expansion would look like :${var2:-`date %m%d%y`}
is this correct syntax? Sorry Im not at a terminal.
 
to assign a default value:
: ${var2:=$(date %m%d%y)}

to use a default value:
${var2:-$(date %m%d%y)}

---------------------------------------------------------------
${parameter:-word}
Use Default Values. If parameter is unset or null,
the expansion of word will be substituted; other-
wise, the value of parameter will be substituted.

${parameter:=word}
Assign Default Values. If parameter is unset or
null, the expansion of word will be assigned to
parameter. In all cases, the final value of param-
eter will be substituted. Only variables, not
positional parameters or special parameters, can
be assigned in this way.
vlad
+---------------------------+
|#include<disclaimer.h> |
+---------------------------+
 
Vlad:

Good description of setting a default. Have a star.

Also, i'd like to update my string comparision post.

Either use an if statement:

if [ -z &quot;$var2&quot; ]; then
var2=&quot;defaultvalue&quot;
fi

or

[ -z &quot;$var2&quot; ] && var2=&quot;defaultvalue&quot;

Regards,

Ed
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top