I'm currently working on an assignment where I have a script that is basically just getting to learn using grep with different regex's.

I have the script written except for the first part where I am asked to take a file as input and then the script runs based on that file.

I have the prompt for input, the read command after, the grep commands. Everything works fine, I just need to implement an if statement I believe that would run the script if it only has 1 parameter given. - The assignment says that the script should only run if 1 and only 1 parameter is given otherwise it should display an error message.



1 Answer 1


Within a script $# will expand to the number of positional parameters. We can use that to check if the correct number of options have been passed, and exit right away if not:


if [ "$#" -ne 1 ]; then
    printf 'ERROR! You must provide one and only one argument!\n' >&2
    exit 1

Places you can read about this:

2.5.1 Positional Parameters

The if Conditional Construct

2.7.2 Redirecting Output

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .