限制Bash参数?

时间:2014-09-17 21:42:35

标签: bash arguments getopts

这是我的bash脚本,非常简单,目前没有任何内容:

#!/bin/bash

NO_ARGUMENTS=0
ARG_ERROR=10

if [ $# -eq "$NO_ARGUMENTS" ]
then
  echo "Usage: `basename $0` options (-h -C -m)"
  exit $ARG_ERROR
fi

helpscreen()
{
echo
echo "========================"
echo "Help Screen:"
echo "Available Arguments:"
echo "-h - Displays this screen"
echo "-C - Complete Install"
echo "-m - Minimal Install"
echo "========================="
echo 
}

completeinstall()
{
echo "Complete Install Initiating"
}

minimalinstall()
{
echo "Minimal Install Initiating"
}

while getopts ":hCm" Option
do
  case $Option in
    h) helpscreen;;
    C) completeinstall;;
    m) minimalinstall;;
    *) echo "Option Not Available.";;
  esac
done

exit

正如您所看到的,只有在选择./test.sh -h,-C或-m时才会运行选项。我的问题是用户可以选择-Cm并让它运行完整和最小安装。如何编辑此项以阻止此类事件发生/限制选项。

1 个答案:

答案 0 :(得分:1)

不要循环,因为你只关心一个选项。

getopts ":hCm" Option
case $Option in
  h) helpscreen;;
  C) completeinstall;;
  m) minimalinstall;;
  *) echo "Option Not Available.";;
esac

或者为每个案例添加break

while getopts ":hCm" Option
do
  case $Option in
    h) helpscreen;      break;;
    C) completeinstall; break;;
    m) minimalinstall;  break;;
    *) echo "Option Not Available.";;
  esac
done

exit