How to create a flag with getopts to run a command

寵の児 提交于 2019-12-13 11:06:37

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/11659981/how-to-create-a-flag-with-getopts-to-run-a-command

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!