如果bash脚本中的条件不起作用

时间:2016-08-08 05:45:55

标签: bash

例如:

#!/bin/bash
DIR=`dirname $0 `
Save_DIR="Save"
cd $DIR 

if  [ -d $Save_DIR ];then
     rm  $Save_DIR/*
else
     mkdir  $Save_DIR
fi

 for  i  in  $(ls)
 do
     if  [  $i==$Save_DIR ]
     then
         echo "is same "
     fi
 done

我认为正确的结果是一行“是相同的”,但我们运行它

is same 
is same 
is same 
is same 
is same 
is same 
is same 
is same 
is same 
is same 

似乎代码if什么都不做,为什么?

1 个答案:

答案 0 :(得分:1)

这必须进行测试[ -n $i==$Save_DIR ],测试字符串是非空的,因为你没有在=周围提供任何空格。

你需要这样做:

[ "$i" = "$Save_DIR" ]

==是bash-ism,但[并非如此,您应该使用=,但如果您使用的是bash,则可以使用[。使用ls时引用变量以防止分词和文件名扩展。

另外不要解析for i in * ,你可以在这里轻松使用shell globbing:

for i in */

仅匹配目录:

    private void button1_Click(object sender, EventArgs e)
    {
        classA A = new classA("test");
        classB B = new classB();

        foreach (var field in A.GetType().GetProperties())
        {
            PropertyInfo pi = B.GetType().GetProperty(field.Name);
            pi.SetValue(B, field.GetValue(A, null));
        }

    }

public class classA{
    public string name { get; set; }

    public classA(string name)
    {
        this.name = name;
    }
}

public class classB
{
    public string name { get; set; }
}