2

This question is a followup on Set environment variable in shell script/access in Java program. I am trying to fetch the environment variable in Java after running a shell script but unable to do so

Shell Script: getDetails.sh:

#!/bin/bash
# File: getDetails.sh
export userDetails="USER123"
# echo "User Details for App :$userDetails"

Java method:

String details = new String("source " + "getDetails.sh");
ProcessBuilder processBuilder = new ProcessBuilder("/bin/bash", "-c", details);
Process getPwdProc = processBuilder.start();
System.out.println("Details - " + processBuilder.environment().get("userDetails"));

The java method returns/prints null for the environment variable - userDetails.

P.S. - Please note that the use of InputStream/BufferedReader to read the userDetails is not possible here as echoing the details is not allowed for the program/organization.

0

1 Answer 1

6

Exporting an environment variable from a bash process does not make it "global", it means that it is inherited (copied) to child processes. That is, processes run by the bash process which exported it.

Here Java is the parent, and there is no (legal) way to inject a variable into a parent process from a child. The variable has to be set and exported before the Java is run.

I suggest a "wrapper" bash script that first exports the variable and then runs your Java application.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @cdarke, your comment is indeed helpful. I exported the variable from parent bash that was calling java: such that export script is now the parent and java is the child process. With this change, I have the environment variable available in java code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.