如何在Java中调用Shell脚本并为脚本变量赋值?
Hey there! Let’s break down exactly how to handle your scenario—getting that shell script on your Windows D: drive set up with proper permissions, then injecting the Src, Dest, and Env variables from a Java class.
1. First: Make Sure the Script Has Execution Permissions
On Windows, if you’re running .sh scripts via WSL (Windows Subsystem for Linux) or Git Bash, you’ll need to grant executable permissions first. You can do this directly from Java without manually messing around in a terminal:
import java.io.IOException; public class ScriptPermissionSetup { public static void main(String[] args) throws IOException, InterruptedException { // Map your Windows D: path to WSL format (e.g., D:/scripts/myScript.sh becomes /mnt/d/scripts/myScript.sh) String scriptPath = "/mnt/d/scripts/myScript.sh"; // Run the chmod command to add execute permissions Process chmodProcess = new ProcessBuilder("bash", "-c", "chmod +x " + scriptPath).start(); chmodProcess.waitFor(); // Wait for the permission change to finish } }
If you’re using something like Cygwin instead, the logic stays similar—just adjust the path format to match your tool’s expectations.
2. Set Src, Dest, Env Variables from Java & Run the Script
There are two straightforward ways to pass these variables to your shell script from Java. Both work great, pick whichever fits your workflow better:
Option 1: Use ProcessBuilder’s Environment Map
This method lets you modify the environment variables that the script will have access to:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Map; public class ScriptVariableInjector { public static void main(String[] args) throws IOException, InterruptedException { String scriptPath = "/mnt/d/scripts/myScript.sh"; // Initialize the process builder to run your script ProcessBuilder pb = new ProcessBuilder("bash", scriptPath); // Grab the environment map and add your variables Map<String, String> scriptEnv = pb.environment(); scriptEnv.put("Src", "/your/source/path"); scriptEnv.put("Dest", "/your/destination/path"); scriptEnv.put("Env", "production"); // Or "dev", "staging", etc. // Start the script process Process scriptProcess = pb.start(); // Read the script's output to verify everything works BufferedReader outputReader = new BufferedReader(new InputStreamReader(scriptProcess.getInputStream())); String line; while ((line = outputReader.readLine()) != null) { System.out.println("Script Output: " + line); } // Wait for the script to finish and check the exit code int exitCode = scriptProcess.waitFor(); System.out.println("Script exited with code: " + exitCode); } }
Option 2: Pass Variables Directly in the Execution Command
If you prefer a more concise approach, you can pass the variables right in the command string that launches the script:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class DirectVariablePassing { public static void main(String[] args) throws IOException, InterruptedException { String scriptPath = "/mnt/d/scripts/myScript.sh"; // Build the command with variables prefixed String command = String.format("Src=%s Dest=%s Env=%s %s", "/your/source/path", "/your/destination/path", "production", scriptPath); ProcessBuilder pb = new ProcessBuilder("bash", "-c", command); Process scriptProcess = pb.start(); // Same output reading and exit code check as Option 1 BufferedReader outputReader = new BufferedReader(new InputStreamReader(scriptProcess.getInputStream())); String line; while ((line = outputReader.readLine()) != null) { System.out.println("Script Output: " + line); } int exitCode = scriptProcess.waitFor(); System.out.println("Script exited with code: " + exitCode); } }
Quick Important Notes
- Path Formatting: Remember, when using WSL, your Windows D: drive lives at
/mnt/d/. For Git Bash, you can use eitherD:/scripts/myScript.shor/d/scripts/myScript.sh. - Script Variable References: Double-check your shell script uses
$Src,$Dest, and$Envto reference these variables (right now your script just has the variable names alone). For example, update your script to:path=`xxx` echo "$path" echo "Source Directory: $Src" echo "Target Directory: $Dest" echo "Environment: $Env" - Error Handling: In production code, add try-catch blocks to handle cases like the script not existing, permission issues, or the script failing to run.
内容的提问来源于stack exchange,提问作者Pritam Kumar

