0

When I run the below code with exact two arguments, the else block doesn't get executed.

If I take out the if else block out of the function, everything works fine.

#!/bin/bash
usage() {

if [[ $# -gt 2 || $# -lt 2 ]]; then
        echo "insufficient args"
else
        if [[ $# -eq 2 ]]; then
                echo "continuing with the script"
        fi
fi

}

usage
4
  • 2
    The problem is that usage is receiving 0 arguments. Call usage with: usage $@ Commented May 8, 2020 at 3:21
  • 1
    @Peter Ho Thank you! That was it. Commented May 8, 2020 at 3:24
  • No problem! If you could accept my answer, I'd appreciate it. Commented May 8, 2020 at 3:27
  • 1
    Use usage "$@", not usage $@. See mywiki.wooledge.org/Quotes#When_Should_You_Quote.3F Commented May 8, 2020 at 4:12

1 Answer 1

1

In this situation, the function usage is receiving 0 arguments from the call.

Change the call to usage $@, which will pass the command line arguments to the usage function.

#!/bin/bash
usage() {

if [[ $# -gt 2 || $# -lt 2 ]]; then
        echo "insufficient args"
else
        if [[ $# -eq 2 ]]; then
                echo "continuing with the script"
        fi
fi

}

usage "$@"
Sign up to request clarification or add additional context in comments.

1 Comment

You should always quote arrays, including $@. So this should be usage "$@", not usage $@.

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.