问题
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'swhile
. 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 shiftOPTIND
. - 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 changeusage
in your\?)
case to anecho
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