开发者

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开发者_如何学Python 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!


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".


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


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'}.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜