Nested-If statements in Shell-scripting

蹲街弑〆低调 提交于 2019-12-25 08:58:03

问题


This is my script:

echo "Name"

read name

if [ "$name" == "abcd" ]; then

 echo "Password"

 read password

 if [ "$password == "pwd" ]; then

  echo "Hello"

 else

  echo "Wrong password"

 fi

else

 echo "wrong username"

fi

And this is the output I get when I run it:

sh hello.sh

Name

abcd

hello.sh: line 14: unexpected EOF while looking for matching `"'

hello.sh: line 16: syntax error: unexpected end of file

Any idea whats wrong here? This could be a very silly one, but i wasted almost an hour on it.


回答1:


if [ "$password == "pwd" ]; then

You have an unmatched " before $password




回答2:


you can use case. Here's an example. You won't want to tell anybody which component is wrong, for security reason.

echo "Name"
read name
echo "Password"
read password
case "${name}${password}" in
 "abcdpwd" ) 
     echo "hello";;
  *) echo "User or password is wrong";;
esac



回答3:


In Shell script.

if condition
    then
        if condition
        then
            .....
            ..
            do this
        else
            ....
            ..
            do this
        fi
    else
        ...
        .....
        do this
    fi



回答4:


if [ "$name" == "abcd" ];
then
  echo "Password"
  read password
  if [ "$password" == "pwd" ];
  then
    echo "Hello"
  else
    echo "Wrong password"
  fi
else
  echo "wrong username"
fi


来源:https://stackoverflow.com/questions/5726839/nested-if-statements-in-shell-scripting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!