Until Loop not working as expected

时间:2015-05-12 23:39:53

标签: linux bash shell debian

I'm currently learning Linux and as an homework, we have to create a few basic shell scripts. Nothing especially complicated but this one is giving me headaches. Here's my code :

package twitbook;
public class Runobject implements Runnable {
public String address;
public Twitbook net;

public Runobject(String theAdress, Twitbook net) {
    address = theAdress;
    this.net = net;

}

@Override
public void run() {
    try {
        URL url = new URL(address);
        URLConnection urlConnection = url.openConnection();

        BufferedReader scanner = new BufferedReader(new InputStreamReader(
                urlConnection.getInputStream()));

        String input = scanner.readLine();
        while (!input.equals("</body>")) {
            if (input.startsWith("<tr> <td>addperson</td>")) {
                input.replaceAll("<tr> <td>addperson</td>", "");
                input.replaceAll(" <td>", "");
                input.replaceAll("</td> </tr>", "");

                net.addUser(input);
            } else if (input.startsWith("<tr> <td>addfriend</td>")) {
                String[] bits = new String[2];
                input.replaceAll("<tr> <td>addfriend</td>", "");
                bits = input.split("</td> <td>");
                input.replaceAll(" <td>", "");
                input.replaceAll("</td> </tr>", "");

                net.friend(bits[0], bits[1]);
                net.friend(bits[1], bits[0]);

            }

            input = scanner.readLine();

        }
        scanner.close();

    } catch (IOException e) {
        System.out.println("bad URL");
    }
    }

}

Basically, I have another script called afficher.sh (I'm french so don't mind the french language used) and it reads whatever file name it gets as a parameter. However, the moment I type "fin", everything is supposed to stop except it still tries to print the file called "fin". I read a bit about the until loop on Internet and once it becomes True, it should stop, which is not my case...

2 个答案:

答案 0 :(得分:1)

检查循环顶部的条件,但是在循环中间输入值。在读取值之后,您要做的下一件事总是将其传递给afficher.sh,然后一旦完成,您可以检查其值以查看是否应该停止。如果您不想在afficher.sh值上运行fin,则需要确保您的控制流允许您在调用afficher.sh之前进行比较。

答案 1 :(得分:1)

就个人而言,我是这样实现的 - 使用while循环,而不是until循环,并单独和明确地检查退出条件:

while true; do
  echo "Enter file name to print out :" ; read toPrint
  [ "$toPrint" = fin ] && break
  sh ./afficher.sh "$toPrint"
done

如果你真的想使用循环条件,你可以这样做:

while echo "Enter file name to print out :";
      read toPrint &&
      [ "$toPrint" != fin ]; do
  sh ./afficher.sh "$toPrint"
done

......但就个人而言,我不太喜欢这种美学理由。