Find the answer to your Linux question:
Results 1 to 3 of 3
Ok, I am trying to muddle my way thru creating a very simple script and having a problem ignoring the case of user input. All I want to do is ...
  1. #1
    Just Joined!
    Join Date
    Apr 2004
    Posts
    5

    [SOLVED] ? on user input for bash script

    Ok, I am trying to muddle my way thru creating a very simple script and having a problem ignoring the case of user input.

    All I want to do is take an existing script, add a piece to have the user verify they want to run the script or not.

    I want to be able to have the user either input yes, YES, or any case combo & have the same result. here is a test script i was using to try it out :

    #!/bin/bash

    ##############################
    # test script for user input to run the script
    #############################

    echo " Are you sure you want to run this script ? Type yes or no and press [ENTER]"
    read response

    if [ "$response" = "yes" ]; then
    ls /tmp
    elif [ "$response" = "no" ]; then
    echo " Taking you back to the Menu"
    fi


    ##########################################

    This works fine as is but I need to add logic to accept Yes, YES, etc.

    I have tried playing with using different operands with read, tried using [Yy][eE][sS] in the $response= section, tried ==, tried alot of different options from reading different reference materials.

    I think I am close but not sure what combo of operands, notation I need to do this correctly.

    Thanks in advance for your help !
    Steve

  2. #2
    Linux Guru
    Join Date
    Nov 2007
    Posts
    1,695
    While you can play with regular expressions, I find it easier to change any input to either all lower or all upper case and then test.

    How to convert a string to upper or lower case in bash?

  3. #3
    Just Joined!
    Join Date
    Apr 2004
    Posts
    5

    My solution

    Thanks very much for the quick reply. Using your link, I was able to get what I needed. For the benefit of others, here is what the final snippet looks like. I also found out that instead of using [:upper:] [:lower:], I could have also used 'A-Z' 'a-z'.

    Thanks Again !
    Steve

    #!/bin/bash

    ##############################
    # test script for user input
    #############################


    echo -n " Are you sure you want to run this script ? Type yes or no and press [ENTER]"

    read answer
    answer="$(echo ${answer} | tr [:upper:] [:lower:])"

    if [ "$answer" != "yes" ]; then
    exit 0
    fi

    #############################
    # Regular Script Continuation here
    ###########################

    ls /tmp

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...