pogba123
pogba123

Reputation: 79

How do i write an unix if-statement for bash script so that user gets error message when they enter invalid filename as argument?

I am creating my own custom command for unix that makes all the arguments inputted executable. At the moment if the user enters a incorrect filename they will get the default error message which is:

chmod: cannot access 'thisisnotafile.txt': No such file or directory

How would i implement an if-statement so that if the user does enter an invalid file name as the argument they would get an error message which i set as part of the if-statement e.g. please enter a valid filename rather than the default one.

Thanks.

Upvotes: 1

Views: 134

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140276

simple (old-style syntax):

if [ ! -f "$the_file" ] ; then
  echo "$the_file: does not exist / not such file"
  exit 1
fi
chmod u+w "$the_file"

To prompt the user for a valid file you can do that in a loop:

printf "enter a file: "
while [ 1 ]
do
read -r the_file
if [ ! -f "$the_file" ] ; then
  echo "$the_file: does not exist / not such file"
else
   break
fi

done
chmod u+w "$the_file"

Upvotes: 3

Related Questions