Search code examples
linuxbashshellunixsh

How to ask user input again and get new value if validation fails?


In my program I need to validate user input getting by "read" in shell script. It check user input has spaces and if validation fails we should give user a another chance to input again.

stringValidator() {  
  if [[ ${1} =~ " " ]]; then
    echo Should not contain spaces
    echo Enter Again!    
    read input
    echo $2=$input 
    return $2   
  else 
    return $1  
  fi
}


echo "Enter below details"
echo -e "client-id :"
read clientId
stringValidator "$clientId" ${!clientId@}

Here I tried to do was send the variable name also into stringValidator() and reassign value to that name (here it is clientId).

But the problem is I can't return that variable from stringValidator(). I use many read inputs though I showed only one here. Therefore I need a separate function for validation.

If you have better way to do this please mention.


Solution

  • The statement "return" is not used like that, it's to send back an error code (numerical).

    That code should do what you want though :

    #!/bin/bash
    
    echo "Enter below details"
    
    while true; do
        echo -n "client-id : "
        read clientID
        if [[ $clientID =~ " " ]]; then
            echo "ClientID Should not contain spaces"
            continue
        else
            break
        fi
    done
    
    echo "do something else"
    

    EDIT

    To answer your comment, this code in ksh would do what you ask :

    #!/bin/ksh
    
    function stringValidator
    {
    
    typeset locVarName
    typeset locVar
    
    locVarName=$1
    nameref locVar=$1
    
    while true; do
        if [[ $locVar =~ " " ]]; then
            echo "$locVarName should not contain spaces"
            echo -n "$locVarName : "
            read locVar
            continue
        else
            break
        fi
    done
    }
    
    echo "Enter below details"
    echo -n "Client-ID : "
    read clientId
    stringValidator "clientId"
    echo "Final value is $clientId"
    
    echo "do something else"
    

    Running would result to something like that :

    Enter below details
    Client-ID : test t
    clientId should not contain spaces
    clientId : tesgg
    Final value is tesgg
    do something else
    

    Hope it helps !