0

Im trying to implement cron job, I learned the getopts from here. My requirement is if I give the argument while triggering then take that value else assign a default value.

My script

ALPHA=unset
BETA=unset
CHARLIE=unset
DELTA=unset

usage()
{
  echo "Usage: alphabet [ -a | --alpha ] [ -b | --beta ]
                        [ -c | --charlie CHARLIE ] 
                        [ -d | --delta   DELTA   ] filename(s)"
  exit 2
}

PARSED_ARGUMENTS=$(getopt -a -n alphabet -o abc:d: --long alpha,bravo,charlie:,delta: -- "$@")
VALID_ARGUMENTS=$?
if [ "$VALID_ARGUMENTS" != "0" ]; then
  usage
fi

echo "PARSED_ARGUMENTS is $PARSED_ARGUMENTS"
eval set -- "$PARSED_ARGUMENTS"
while :
do
  case "$1" in
    -a | --alpha)   ALPHA=1      ; shift   ;;
    -b | --beta)    BETA=1       ; shift   ;;
    -c | --charlie) CHARLIE="$2" ; shift 2 ;;
    -d | --delta)   DELTA="$2"   ; shift 2 ;;
    # -- means the end of the arguments; drop this, and break out of the while loop
    --) shift; break ;;
    # If invalid options were passed, then getopt should have reported an error,
    # which we checked as VALID_ARGUMENTS when getopt was called...
    *) echo "Unexpected option: $1 - this should not happen."
       usage ;;
  esac
done

echo "ALPHA   : $ALPHA"
echo "BETA    : $BETA "
echo "CHARLIE : $CHARLIE"
echo "DELTA   : $DELTA"
echo "Parameters remaining are: $@"

Here even if give value for -a its not accepting instead it's still showing 1 as the output. If I give a value (-a somevalue) then it should take that value else to take the value I assign at the first line unset.

TheDataGuy
  • 2,712
  • 6
  • 37
  • 89
  • That's normal; since `a` is not followed by a `:` in the `abc:d:` optstring. But the title says `getopts` (a standard shell builtin), and you're using `getopt` (a non-standard standalone implementation). –  Apr 13 '20 at 11:07
  • getopts will help to solve this issue? – TheDataGuy Apr 13 '20 at 11:10
  • No, with getopt or getopts, you should use `a:bc:d:` instead of `abc:d:` if you want the `-a` option to take an argument. And also change the `ALPHA=1; shift ` to `ALPHA=$2; shift 2` just like with `-c` / `CHARLIE`, etc. –  Apr 13 '20 at 11:11

0 Answers0