23

I'm creating a very simple sh file to do something, but I want to pass an argument without a value, for example:

./fuim -l

But I receive the following message:

./fuim: option requires an argument -- l

If I pass a random value, like ./fuim -l 1, it works perfectly. How can I do that?

Here's what I have so far:

while getopts e:f:l:h OPT
do
    case "$OPT" in
        h) print_help ;;
        e) EXT=$OPTARG ;;
        f) PROJECT_FOLDER=$OPTARG ;;
        l) LIST_FILES=1 ;;
        ?) print_help ;;
    esac
done

shift $((OPTIND-1))

if [ -z "$EXT" ] || [ -z "$PROJECT_FOLDER" ]; then
    print_help
fi
1
  • 1
    So it's a mandatory argument option. Optional argument options use two colons (:) instead of one (as in getopts e:f:l::h), look the manual of getopts(1) for that, as there's some side effects when you use optional argument options. Commented Aug 13, 2014 at 6:37

1 Answer 1

51

When using getopts, putting : after an option character means that it requires an argument. So change l: to l, as in:

while getopts e:f:lh OPT

This makes it a boolean option, either it's there or it isn't.

Sign up to request clarification or add additional context in comments.

2 Comments

Went through multiple blog, but no one has mentioned about the : behaviour. Thanks for explaining.
Those must be pretty bad tutorials, as this is one of the most basic features.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.