简体   繁体   中英

How to assign a value into a variable in a shell script from a java code

I have a variable parameter ( retrieved from a getText field in Seleium Automation) that i want to assign the value into a specefic place in a shell script :

In java this is what i do :

String ref = workcreation.getfield_ref().getText(); 


  try {  ProcessBuilder pb = new ProcessBuilder("/home/script.sh");
            Process p = pb.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null)
            {
                System.out.println(line);

                System.out.println("in " + reader);

            }
            p.waitFor();

        }
        catch (IOException e)
        {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

In script script.sh, i want to assign the value of ref into the parameter &ref in that exact place :

##it is the value of &ref that i want to get 
if [  -d "/data/techVersion_$ref" ]; then
echo "le dossier  existe dans cccc "

else
echo " le dossier  n'existe pas dans  cccc !"
exit
fi

what can i do?

You can pass arguments to your command/script by ProcessBuilder.

In your shell script, you can read the argument. A simple example is:

ProcessBuilder pb = new ProcessBuilder("/home/script.sh", "hello");

in your script:

echo "variable set in java: $1"

The ProcessBuilder takes an arbitrary number of String s as arguments. The first one has to be the executable itself, in your case it is the script "/home/script.sh" . You are currently just passing the executable as a single argument. Just add the parameters for your script to the constructor call of ProcessBuilder .

Your line

ProcessBuilder pb = new ProcessBuilder("/home/script.sh");

should be replaced by this

ProcessBuilder pb = new ProcessBuilder("/home/script.sh", "firstArg", "secondArg");

or you create a List<String> containing the executable as first element followed by the parameters, like

List<String> execPlusArgs = new ArrayList<String>();
execPlusArgs.add("/home/script.sh");
execPlusArgs.add("firstArg");
execPlusArgs.add("secondArg");
ProcessBuilder pb = new ProcessBuilder(execPlusArgs);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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