A
A
Alexey Yarkov2016-11-18 15:49:51
bash
Alexey Yarkov, 2016-11-18 15:49:51

How to understand getopt in bash?

I found an example of working with getopt and finished it up a bit for an example:

#!/bin/bash

ARGS=$(getopt -o hvfd: --long help,verbose,file:,directory: -- "[email protected]")

if [ $? != 0 ] ; then
  echo "Terminating..." >&2;
  exit 1;
fi


eval set -- "$ARGS"

HELP=false
VERBOSE=false
FILE=
DIRECTORY=

while true; do
  case "$1" in
  -h | --help )		HELP=true;			shift ;;
  -v | --verbose )	VERBOSE=true;		shift ;;
  -f | --file )		FILE="$2";			shift 2 ;;
  -d | --directory )	DIRECTORY="$2";		shift 2 ;;
  -- )				shift;				break ;;
  * ) break ;;
  esac
done

if [ ${HELP} ]; then
  echo "ARG: \${HELP}=${HELP}"
fi
if [ ${VERBOSE} ]; then
  echo "ARG: \${VERBOSE}=${VERBOSE}"
fi
if [ ${FILE} ]; then
  echo "ARG: \${FILE}=${FILE}"
fi
if [ ${DIRECTORY} ]; then
  echo "ARG: \${DIRECTORY}=${DIRECTORY}"
fi

Run :
$ ./argtest.sh -hv -f /tmp/lock -d ~/bin
Result :
ARG: ${HELP}=true
ARG: ${VERBOSE}=true
ARG: ${FILE}=-d

Question : WTF?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Yarkov, 2016-11-18
@yarkov

I found a jamb))))
In line
In hvfd: you need to put a colon after f ))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question