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
336 views
in Technique[技术] by (71.8m points)

bash - How to create a flag with getopts to run a command

I need help with my getopts, i want to be able to run this command ( mount command) only if i pass a flag ( -d in this case). below output is what i have on my script but it doesn't seem to work.

CHECKMOUNT=" "

while getopts ":d" opt
do
  case "$opt" in

  d) CHECKMOUNT="true" ;;

      usage >&2
      exit 1;;
    esac
   done
  shift `expr $OPTIND-1`

FS_TO_CHECK="/dev" 

if [ "$CHECKMOUNT" = "true" ] 
then
  if cat /proc/mounts | grep $FS_TO_CHECK > /dev/null; then
   # Filesystem is mounted
else
   # Filesystem is not mounted
  fi
fi

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Your script has a number of problems.

Here is the minimal list of fixes to get it working:

  • While is not a bash control statement, it's while. Case is important.
  • Whitespace is important: if ["$CHECKMOUNT"= "true"] doesn't work and should cause error messages. You need spaces around the brackets and around the =, like so: if [ "$CHECKMOUNT" = "true" ].
  • Your usage of getopts is incorrect, I'm guessing that you mistyped this copying an example: While getopts :d: opt should be: while getopts ":d" opt.
  • Your usage of shift is incorrect. This should cause error messages. Change this to: shift $((OPTIND-1)) if you need to shift OPTIND.
  • The bare text unknocn flag seems like a comment, precede it with #, otherwise you'll get an error when using an unknown option.
  • There is no usage function. Define one, or change usage in your ?) case to an echo with usage instructions.

Finally, if your script only requires a single optional argument, you might also simply process it yourself instead of using getopt - the first argument to your script is stored in the special variable $1:

if [ "$1" = "-d" ]; then
    CHECKMOUNT="true"
elif [ "$1" != "" ]; then
    usage >&2
    exit 1
fi

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

...