java shell 变量,将变量从Java传递到Shell脚本

I am trying to run a shell script from a Java code. At the moment I am providing data manually in the script, but I would like to be able to provide the variables from the Java code that runs the script.

This is the Java code and the script:

public static void main(String[] args) {

try {

ProcessBuilder pb = new ProcessBuilder(

"/home/najib/upload.sh");

Process p = pb.start();

p.waitFor();

System.out.println("Script executed successfully");

} catch (Exception e) {

e.printStackTrace();

}

}

The shell code:

#!/bin/bash

/usr/local/virtuoso-opensource/bin/isql 1111 dba dba exec="set AUTOCOMMIT MANUAL;"&

/usr/local/virtuoso-opensource/bin/isql 1111 dba dba exec="delete from DB.DBA.load_list;"&

/usr/local/virtuoso-opensource/bin/isql 1111 dba dba exec="SPARQL CREATE GRAPH ;"&

/usr/local/virtuoso-opensource/bin/isql 1111 dba dba exec="ld_dir('/home/najib', 'VAR2', 'VAR1');"&

wait

/usr/local/virtuoso-opensource/bin/isql 1111 dba dba exec="rdf_loader_run();"

I would like to know where I can put the variables in the Java code, and how to then call it in run time!

Edit:

Based on the solutions provided, I changed the script to this:

/usr/local/virtuoso-opensource/bin/isql 1111 dba dba exec="SPARQL CREATE GRAPH ;"&

/usr/local/virtuoso-opensource/bin/isql 1111 dba dba exec="ld_dir('/home/najib', '$1', '$2');"&

I also added an echo at the end of the script to see if the variables are being passed correctly, and it seems that they are. The first command (the SPARQL one) seems to work as the graph is indeed created, but the second one is not processed correctly..

解决方案

You can pass params to your shell script and use them inside de script, The Class ProcessBuilder have a constructor that take the command to execute and the list of parameters to pass to the executable :

ProcessBuilder(String... command)

you have to pass params like this :

ProcessBuilder pb = new ProcessBuilder("/home/najib/upload.sh",param1,param2,param3);

inside the script param1 is $1 , param2 is $2 , and param3 is $3 (you can pass in the constructor as many arguments as you want )

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值