简体   繁体   中英

How to insert in shell script from java index

I am using Java to run a sh file.

However, the question is how to put Java's variables into a sh variable while executing the sh file for Eclipse.

I am using eclipse.

Here is my code

test.sh
#!/bin/sh
docker run -it --name $1 ubuntu:16.04
exit 0

In java

public static void makeContainer() throws Exception {
    //String makecontainer = "/usr/local/bin/docker run --name "+fileName+" ubuntu:16.04";

    String[] command = { "/bin/sh","/Users/keomgong1/Desktop/test.sh", fileName };
    Process process = Runtime.getRuntime().exec(command);

    process.getInputStream();
    InputStream is = process.getInputStream();
    BufferedReader bf = new BufferedReader(new InputStreamReader(is));

}

I want $1 as filename but it is not running as expected.

filename is java string index.

What's wrong?

What can I do?

The first argument after the script name is the program name ( $0 ), instead of the first positional parameter ( $1 ).

You can add a dummy filename for $0 and then your next parameter will be $1 :

String[] command = { "/bin/sh","/Users/keomgong1/Desktop/test.sh", "_", fileName };

However, it is better to run the script directly instead of with /bin/sh :

String[] command = { "/Users/keomgong1/Desktop/test.sh", fileName };

This requires test.sh to have a shebang (first line is #!/bin/sh ) and execute permissions ( chmod +x /Users/keomgong1/Desktop/test.sh ).

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