How to Check for the Correct Number of Arguments After Flags in a Bash Script?

April 22, 2025 2 answers
Asked by Twizzle
I'm working on a Bash script that accepts multiple flags. I want to enforce a rule where if the `-a` flag is used, it should only allow one argument after the command. So for example, `./script -a list` should work, but `./script -a list somethingHere` should return an error. I am currently checking if `$3` is empty when `-a` is specified, but this fails when users write commands like `./script -a -s list`, as `$3` won't be empty. All I need is to determine dynamically if the `$n+1` (after `list`, indicated by `$n`) is empty. Any ideas on how to achieve this?

Answers

6pm ceramics
You might want to try using `getopt` instead of `getopts`, especially if you need to deal with more complex flag setups. It supports long options, which can be quite handy. The downside is that my experience with `getopt` isn't extensive, so best of luck exploring that direction!

Twizzle: Yeah, I'm currently using `getopts`, but I only know how to verify that an argument is present with a flag, not that I can limit the number of arguments per flag. Thanks for pointing me in the right direction!

Reply to this answer
R3_pullup
Typically in shell scripting, after handling an argument, you can use `shift` to remove it from the argument list. This allows you to work with `$1` (and maybe `$2`) while checking how many arguments are left using `$#`. It helps in cleanly managing the input arguments, so definitely give that a shot!
Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions