user2860658
user2860658

Reputation: 153

Comparing variable to grep statement

I am trying to make the statement pass as true, if and only if the user input through stdin is within the guidelines of

[a-z_][a-z0-9_-]*

so if the user were to input a % or $ in their argument passed then it would return false. How could i go about that?

Upvotes: 2

Views: 176

Answers (2)

John1024
John1024

Reputation: 113854

This reads from stdin and reports on true or false status (and exits if it is false):

grep -q '^[a-z_][a-z0-9_-]*$' && echo true || { echo false; exit 1 ; }

If grep finds a match to your regex, it sets its exit code to true (0) in which case the "and" (&&) clause is executed and "true" is returned. If grep fails to find a match, the "or" (||) clause is executed and "false" is returned. The -q flag to grep tells grep to be quiet.

If one were to use this in a script, one would probably want to capture the user input into a shell variable and then test it. That might look like:

read -p "Enter a name: " var
echo "$var" | grep -q '^[a-z_][a-z0-9_-]*$' && echo true || { echo false; exit 1 ; }

To make it easy to add more statements to execute if the result is "true", we can write it out in a longer form with a place marked to add more statements:

read -p "Enter a name: " var
if echo "$var" | grep -q '^[a-z_][a-z0-9_-]*$'
then
    echo true
    # other statements to execute if true go here
else
   echo false
   exit 1
fi

Upvotes: 4

kojiro
kojiro

Reputation: 77127

The answer depends on what you mean by return. If by return you mean literal false, well, you have a small problem: UNIX scripts can only return an integer in the range 0-255. Normally in UNIX when a program returns it returns an exit status that indicates (among other things) the success or failure of the program. So you could just write:

grep -q ''^[a-z_][a-z0-9_-]*' || exit

At the top of your script. Since a shell script exits with the last value of $? anyway, that would only exit if the grep fails, and would exit with the same exit code as the grep statement itself. Technically this would mean returning 1, but in UNIX that would be akin to false. If the grep succeeds, the script would continue, not returning anything until completion or another error condition occurs.

If what you really want is to print the string "false", then see John1024's answer.

Upvotes: 2

Related Questions