سؤال

I am having a critical trouble to execute a shell script which contains a while loop. Here is my shell script:

echo Here 1
sleep 0.05
echo Here 2
sleep 0.05
echo Here 3

ic=70
while [ $ic -ge 40 ]
do
        #sleep 0.05
        ic=$[$ic-1]
        echo Here $ic
done

When I am executing the script normally from the terminal as /home/pi/tbe/testSleep.sh it is working. and printing all the echos.

Now I have written this java method to execute the file:

public static void main(String[] args) throws IOException, InterruptedException {       
    String command = "/home/pi/tbe/testSleep.sh";
    System.out.println("Executing command: " + command);

    Process process = new ProcessBuilder(command).start();

    BufferedReader reader = new BufferedReader(new InputStreamReader(
            process.getInputStream()));
    String line = null;

    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }

    process.waitFor();
    int exitValue = process.exitValue();
    System.out.println("Command executed. Exit value: " + exitValue);
    process.destroy();  
}

And when I am executing it I can only see the following output:

Executing command: /home/pi/tbe/testSleep.sh
Here 1
Here 2
Here 3
Here $[70-1]
Command executed. Exit value: 0

This is really weird. Any pointer would be very helpful to me.

هل كانت مفيدة؟

المحلول

It seems that the shell executing the command is not same as that you are using to run the script on command line. Specify the shell as bash.

Add shebang in the script (as first line). It is always a good practice to be specific about the shell in the script

#!/bin/bash

You could also specify the shell you want to use for the shell script

String[] command = {"/bin/bash", "/home/pi/tbe/testSleep.sh"};

نصائح أخرى

I ran your script in Ubuntu:

$ sh script.sh
Here 1
Here 2
Here 3
Here $[70-1]
script.sh: 8: [: Illegal number: $[70-1]

Apparently $[70-1] is not being evaluated but simply treated as a literal...

I saw the comments after I saved. They are correct. Using bash (I was lazy) gives the correct results.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top