简体   繁体   English

如何通过Java代码将值分配给Shell脚本中的变量

[英]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 : 我有一个变量参数(从Seleium Automation中的getText字段检索),我想将值分配给shell脚本中的特定位置:

In java this is what i do : 在Java中,这就是我的工作:

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 : 在脚本script.sh中,我想在该确切位置将ref的值分配给参数&ref:

##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. 您可以通过ProcessBuilder将参数传递给命令/脚本。

In your shell script, you can read the argument. 在您的Shell脚本中,您可以读取参数。 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. ProcessBuilder采用任意数量的String作为参数。 The first one has to be the executable itself, in your case it is the script "/home/script.sh" . 第一个必须是可执行文件本身,在您的情况下,它是脚本"/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 . 只需将脚本的参数添加到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>其中包含可执行文件作为第一个元素,后跟参数,例如

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

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

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