ive implemented getopt for the command line but have this problem,
#!/bin/sh
text=""
set -- getopt "t" etc .... #sets arguments
while :
do
case "$1" in #gets arguments
-t: shift; text="$1" ;;
shift
done
shift
if [ $text = "" ]
then
echo "no text"
else
echo "text"
fi
when i run the program ./script -t <text>
it prints "text"
but when i just run ./script
it returns a "arguments expected" message, (shouldnt it return "no text" ?)
is there a way to fix this, i want to be able to run ./script without it complaining as well as ./script -t <text>
Since you are using case statements, you should close the case statements with esac
Your script would now look like this:
do
case "$1" in #gets arguments
-t: shift; text="$1" ;;
esac
done
Regarding your use of shift indicates that the script requires you to input arguments. From the man pages we have the following:
shift [n]
The positional parameters from n+1 ... are renamed to $1 ....
Parameters represented by the numbers $# down to $#-n+1 are
unset. n must be a non-negative number less than or equal to
$#. If n is 0, no parameters are changed. If n is not given,
it is assumed to be 1. If n is greater than $#, the positional
parameters are not changed. The return status is greater than
zero if n is greater than $# or less than zero; otherwise 0.
Also your sciprt has a $1 which actually in scipt-terminology refers to the first argument.
No arguments + your script = "arguments expected"
It is always a good idea to check whether the user has provided any arguments at all.
$# gives you the count of the number of arguments provided at command line.
You script should be tweaked like this:
#! /bin/sh
if [ $# -eq 0 ] ; then
echo "No text"
else
while :
do
case "$1" in #gets arguments
-t: shift; text="$1" ;;
shift
done
shift
echo "Text"
fi
thanks for that, that was quite informative.
just wandering how would that script be modified if say there
were multiple arguments?
e.g
arguments "t:w"
if theres no -t
do something
else
do something else
if theres no -w
do something
else
do something else
etc ...