How to validate if the file not passed in

Viewed 28

So I have script that takes file from user with option -y or -n and -d is required script runs ./example.sh -d file -y or -n variable

file=""

I need to do validation on if the user did not pass file in for example

./example.sh -y       --- it should give error "must provide file"`
./example.sh -n       --- it should give error "must provide file"`
./example.sh -d       --- it should give error "must provide file"
./example.sh -y -n       --- it should give error "must provide file"

i came up with this but its not working #checking if the file is provided

if [ $file -eq 1 ]; then
    echo "No file provided"
    exit 1
fi
# Does the file exist 
which works for checking if the file exists but it only check if the file in there

  if [[ ! -f $file ]]; then
      echo
      echo "Error: The file $file does not exist."
        exit 1
    fi
1 Answers

Why not simply loop over the arguments and test the -d, -n and -y options in a case statement. The filename must follow the -d option as I understand it. When the -d option is processed in your case statement check that the next argument holds a filename that exists on the system and is non-empty, if so, set the filename, e.g. filename="${argv[i+1]}".

When you exit the option processing loop, simply test if filename is set and you have your answer.

A short example could be:

#!/bin/bash

argc=$#         ## argument count
argv=("$@")     ## array holding arguments (argument vector)

filename=       ## filename is empty

## loop over all arguments, filename must follow -d 
for ((i = 0; i < argc; i++)); do
  case "${argv[i]}" in
        ## file exists and non-empty, set filename to argument
    -d ) [ -s "${argv[i+1]}" ] && { filename="${argv[i+1]}"; };;
    -n ) # do whatever for option n
        ;;
    -y ) # do whatever for option y
        ;;
  esac
done

[ -n "$filename" ] || {   ## check filename set or exit
  printf "error: file empty or not readable.\n" >&2
  exit 1
}

## valid filename received
printf "file '%s' found - script running.\n" "$filename"

Only if a valid filename is given after the -d option will the script run. Otherwise it will give an error message and exit.

Examples

$ ./process-opts.sh -y -n
error: file empty or not readable.

or

$ ./process-opts.sh -y -d -n
error: file empty or not readable.

Finally

$ ./process-opts.sh -y -d README -n
file 'README' found - script running.

or in any order:

$ ./process-opts.sh -y -n -d README
file 'README' found - script running.
Related