1

Suppose I have a script that takes two arguments, is there way to check if there is one argument or 2+ arguments in say the form:

if [ check if arguments don't equal 2 ]; then
    echo Too many arguments
    exit 1
fi
2
  • have you tried "man bash" already? What didn't you understand from the man page? Commented Sep 30, 2012 at 21:11
  • 2
    People who invoke your script with no arguments will be surprised if they get told 'too many arguments'. If you expect exactly two arguments, the message should probably be something like echo "Usage: $0 from to" >&2 which identifies the command (via $0), and the correct usage, and sends the information to standard error (so it doesn't get lost in a pipeline, for example). Most of my scripts use $(basename $0 .sh) to identify the command being run. Commented Sep 30, 2012 at 21:20

1 Answer 1

5
if [ $# -ne 2 ]; then
   # Number of arguments was not 2
fi

The variable $# holds the number of passed arguments.

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

1 Comment

If this is specifically for bash (and not any POSIX-compatible shell in general), the more readable alternative is if (( $# != 2 )); then.

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.