You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java中调用Shell脚本并为脚本变量赋值?

How to Manage a Windows D-Drive Shell Script & Set Variables from Java

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 either D:/scripts/myScript.sh or /d/scripts/myScript.sh.
  • Script Variable References: Double-check your shell script uses $Src, $Dest, and $Env to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 21:48:10