Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

shell - My bash script doesn't print the flags

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...