0

I'm using this :

for example ./imgSorter.sh -d directory -f format

the scripts' content is :

#!/bin/bash
while getopts ":d:f:" opt; do
  case $opt in
    d)
      echo "-d was triggered with $OPTARG" >&2
      ;;
    f)
      echo "-f was triggered with $OPTARG" >&2
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      exit 1
      ;;
    :)
      echo "Option -$OPTARG requires an argument." >&2
      exit 1
      ;;
  esac
done

use cases :

$ ./imgSorter.sh -d myDir -d was triggered with myDir OK

$ ./imgSorter.sh -d -f myFormat -d was triggered with -f NOK : how is it that a string beginning with - is not detected as a flag ?

3

You have told getopts that the -d option should take an argument, and in the command line you use -d -f myformat which clearly (?) says "-f is the argument I'm giving to the -d option".

This is not an error in the code, but in the usage of the script on the command line.

Your code needs to verify that the option-arguments are correct and that all options are set in an appropriate way.

Possibly something like

while getopts "d:f:" opt; do
  case $opt in
    d) dir=$OPTARG      ;;
    f) format=$OPTARG   ;;
    *) echo 'error' >&2
       exit 1
  esac
done

# If -d is *required*
if [ ! -d "$dir" ]; then
    echo 'Option -d missing or designates non-directory' >&2
    exit 1
fi

# If -d is *optional*
if [ -n "$dir" ] && [ ! -d "$dir" ]; then
    echo 'Option -d designates non-directory' >&2
    exit 1
fi

If the -d option is optional, and if you want to use a default value for the variable dir in the code above, you would start by setting dir to that default value before the while loop.

A command line option can not both take and not take an argument.

  • ok thank you @Kusalananda, I wrongly assumed that getopts took every - for the beginning of a flag. – St3an Apr 26 '18 at 14:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.