Looking2learned
Looking2learned

Reputation: 213

Number of arguments requirement input validation

Writing a script to search a file for a pattern and output the lines found with that file and the number of each line.

I have the script as

#!/bin/bash

echo "------ File =" $2 "------"
grep -ne $1 $2

It works just fine, but now I need validation. All I want is how to write

if [[ number of arguments <2 ]]; then
echo "Must enter two arguments"

And something that also does

if [[ $2 is not a file/directory]]; then
echo "second arguemnt needs to be a file/directory"

As always, much love.

Upvotes: 1

Views: 95

Answers (3)

jaypal singh
jaypal singh

Reputation: 77095

For question 1:

if [[ number of arguments <2 ]]; then
echo "Must enter two arguments"

You can do:

if [[ $# -ne 2 ]]
then
  echo "Usage: You must enter two arguments"
  exit -1
fi

For question 2:

if [[ $2 is not a file/directory]]; then
echo "second arguemnt needs to be a file/directory"

You can do:

if [[ ! -e $2 ]]
then
    echo "File does not exist!"
    exit -2
fi

Upvotes: 3

gniourf_gniourf
gniourf_gniourf

Reputation: 46823

Your script works fine until it breaks! if you enter filenames or arguments with spaces or other funny symbols, you'll have funny surprises.

#!/bin/bash

printf -- "------ File = %s ------\n" "$2"
grep -ne -- "$1" "$2"

is already much better (observe the quotes, learn, and use more quotes!). Regarding your tests, you're very close to the solution!

For number of arguments, I'll use shell arithmetic using the variable $#, see the list of special parameters:

if (( $# != 2 )); then
    echo >&2 "Must enter two arguments you dumbo"
    exit 1
fi

To test file or directory, use conditional expressions

if [[ ! -e $2 ]]; then 
    echo >&2 "second argument needs to be a file/directory you dumbo"
    exit 1
fi

Upvotes: 0

Paul Rubel
Paul Rubel

Reputation: 27222

For the number of arguments use $#

if [ $# -lt 2 ]
then
  echo "Too few args"
fi

For the second take a look at test. It has all sorts of things you can test for: -d for a directory and -f for a regular file. There are all sorts of things like symlinks and named pipes you can check for.

Upvotes: 0

Related Questions