0

so in my code below I'm like trying to get my code to read the input that the user enters in my code as seen below

#./MyProject -a -b OR -b -a

However I keep getting a Syntax error and its not passing the tests given by the program: The following tests are: having inputs that aren't a&b (i.e c-z), having no inputs at all, having too little arguments, having too many arguments,

#Use just prints out the format like this : ./MyProject -a -b

 - if ( ! getopts ":ab" arg) then  
echo $use  
fi 

 while [getopts ":ab" arg2] 
do
         case $arg2 in

        t) if (($1 != "t" && $1 != "o")); then
         echo $use 
     fi   
 esac   
done  
}
1
  • Sorry everyone I've been having a hard time trying to convert my code into the coding here.... I don't know how to format it correctly...
    – Bob
    Mar 7, 2017 at 10:38

1 Answer 1

4

The following example should work for you.

#!/bin/bash

usage() {
    echo "Usage: $0 -a -b"
    exit
}

while getopts ":a:b:" arg; do
    case $arg in
        a)
            a=${OPTARG}
            (($a == "t" || $a == "o")) || usage
            ;;
        b)
            b=${OPTARG}
            ;;
        *)
            usage
            ;;
    esac
done

echo $a
echo $b
7
  • Thank you so much daisy for answering so quickly, Do you know tho about having too little arguments?
    – Bob
    Mar 7, 2017 at 11:09
  • too little or none :) if you can let me know i'll appreciate it!
    – Bob
    Mar 7, 2017 at 11:16
  • @Bob you can check arguments using if (($# < 2 )); then usage; fi. Mar 7, 2017 at 11:16
  • Thanks and if there was an extra argument after the list? I tried if (($# > 3 )); then usage; fi but it didn't work
    – Bob
    Mar 7, 2017 at 12:19
  • extra argument (not beeing -a/-b will be caught by *) in case.
    – Archemar
    Mar 7, 2017 at 13:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.