Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am not sure what is wrong with my bash script as it doesn't print the given flags nor it echoes them within case statement:

 26 while getopts ":a:b:p:u" opts;
 27 do
 28   case $opts in
 29     a) echo got an A flag;;
 30     b) echo got an B flag;;
 31     u) user=$OPTARGS echo $user;;
 32     p) pass=$OPTARGS echo $pass;;
 33     ?) echo I don't know what flag is this;;
 34 esac
 35 done
 36 
 37 echo user: $user pass: $pass

This is how I have called it:

bash-4.3$ ./functionexample.sh -p 123 -u mona
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
222 views
Welcome To Ask or Share your Answers For Others

1 Answer

This should work :

while getopts ":a:b:p:u" opts
do
   case $opts in #removed the dot at the end
    a) echo "got an A flag";;
    b) echo "got an B flag";;
    u) user="$OPTARGS"
       echo "$user"
       #double quote the variables to prevent globbing and word splitting
    ;;
    p) pass="$OPTARGS"
    #Passwords can contain whitespace in the beginning.
    #If you don't double quote , you loose them while storing.
    #eg. pass=$@ will strip the leading whitespaces in the normal case.
       echo "$pass"
    ;;
    ?) echo "I don't know what flag is this" 
    #Better double quote to make echo easy, consider something like \\\
    #count the hashes? eh?
    ;;
   esac
done

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...