简体   繁体   English

shell脚本(如果else循环不起作用)

[英]shell script if else loop not working

Given the following programme which reads in user input twice 给定以下程序,该程序两次读取用户输入

function search_grep
{
   if [ "$2" == "" ];then
    for x in "${title[@]}" 
    do
    value=$(echo $x | grep "$1")

        if [ "$value" != "" ];then
        echo "$value"
        fi      

    done
   elif [ "$1" == "" ];then
    hello="123"
    echo "$hello"   

   fi          

}

echo -n "Enter title : "
read book_title

echo -n "Enter author : "
read author

title=(CatchMe HappyDay)
search_grep $book_title $author

it works as expected when i enter 当我进入时它按预期工作 followed by HappyDay HOWEVER 其次是HappyDay HOWEVER

When i enter foo followed by 当我输入foo之后 , I would expect console output to be ,我希望控制台输出为

123 123

instead I am getting 相反,我越来越

Can someone explain to me , the programme is not executing the second elif loop though second input is 有人可以告诉我,尽管第二个输入是

In both of your cases cases, the following: 在两种情况下,以下情况:

search_grep $book_title $author

expands to a call with a single argument. 扩展为带有单个参数的调用。 Hence, the "then" clause is activated. 因此,“ then”子句被激活。 The reason is that an unquoted argument consisting of whitespace expands to nothing and disappears. 原因是由空格组成的无引号引数扩展为零,然后消失。 That is the way of bash. 这就是重击的方法。

If you want to pass search_grep two arguments, then you need to quote the variables: 如果要向search_grep传递两个参数,则需要引用变量:

search_grep "$book_title" "$author"

As shown here , you might try using = instead of == 如图所示在这里 ,你可以尝试使用=代替==

Or for an empty string comparison try -z 或者对于空字符串比较,请尝试-z

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM