seyelent
seyelent

Reputation: 119

Matching New Line - Unix Shell

I am trying to see if a new line has been matched. The reason is that my script asks for the user's name. If they press enter, then a default name is used.

The problem is I cannot seem to check whether they have pressed enter, or used a name of their own. I have searched a lot on the net, and can't find a working answer. Here is what I have tried to implement:

if [ `expr match "$temp1" "\n"` != 0 ]

Very new to this. Thanks!

Upvotes: 1

Views: 196

Answers (3)

holygeek
holygeek

Reputation: 16185

You can use the `read' bash builtin for this:

echo 'what is your name?'; read name; echo Hi ${name:='John'}

That will assign the name "John" as the default name if the user presses enter without entering any name.

I forgot to add that the feature that helps is is the default shell variable value assignment if it is not set ${name:='John'}.

Upvotes: 1

Brian Gerard
Brian Gerard

Reputation: 885

Try something like this:

#!/bin/sh
/bin/echo -n "Who? "
read name
if [ "x$name" != "x" ]
then
    echo "Hi $name"
else
    echo "Hi no-name"
fi

Upvotes: 1

dogbane
dogbane

Reputation: 274612

You don't need to check if they have pressed enter. Just check the length of the string. Example:

if [ -z $input ]
then
    echo "No name was input. Setting default name"
    name=JOE
fi

Alternatively, you can use the following bash syntax to set a variable to a default value:

name=${input:-JOE}

This means that if the variable input is not set, name would be set to the default of "JOE".

Upvotes: 3

Related Questions