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 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

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

1 Answer

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

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