1

I need to make a bash script that takes user input and does some validation.

The input is small. I just need to get a user choice "yes" or "no" and a file path and make sure the input is indeed a filepath and that he entered yes or no.

How can I validate the user input?

0

1 Answer 1

4

from your bash prompt type

help read


example: step 1.

pete@ruthie ~ $ read -p "Yes or No :" ANSWER

Yes or No :Yes

pete@ruthie ~ $ echo $ANSWER

Yes

step 2.

case $ANSWER in 
    Y* | y* ) echo "ANSWER is yes" ;; 
    N* | n*) echo ANSWER is no;; 
     *) echo "Unclear Response" ;; 
esac

ANSWER is yes

Or all on one line:

case $ANSWER in Y* | y* ) echo "ANSWER is yes" ;; N* | n*) echo ANSWER is no;; *) echo "Unclear Response" ;; esac

ANSWER is yes

So something vaguely like::

   read -p "Enter File Name :" FILE_TO_CHECK 

    if [ ! -e "$FILE_TO_CHECK" ]; then 
        echo -e "There is no file called $FILE_TO_CHECK \n please check spelling"
    else
        echo  "Congratulations found $FILE_TO_CHECK. "
         ls -lah $FILE_TO_CHECK
         read -p "Process $FILE_TO_CHECK ? Y or N : PROCEED
           case $PROCEED in
             Y* | y*)
##call function or system command to do something with this data
               foo $FILE_TO_CHECK

             ;;
            * )
             echo -e "Note $USER\n No action taken by $0 on $FILE_TO_CHECK"
             ;;
            esac

    fi

The test command is your friend. You really need to learn its ways ASAP.

help [

and

help test

The "help bashthing" command is a great quick reminder.

see also: the Advanced Bash Scripting Guide (ABS) http://tldp.org/LDP/abs/html/

FWIW: This is a very simple example and wont accommodate much in the way of unexpected user input. I would probably call functions for each step of this as then I could conditionally represent the user with another chance.

The case tests nested like this is plain ugly :) === hard to get neat and read later

There are other ways to achieve all this try zenity for a GTK style GUI.

The A.B.S is excellent but dont try to eat it all at once !

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.