How do I write a batch file which opens the GitBash shell and runs a command in the shell?

前端 未结 6 1154
南方客
南方客 2020-12-01 00:22

I\'m on Windows 7 trying to use a batch file to open the GitBash shell and make a git call. This is the contents of my batch file:

REM Open GitBash 
C:\\Wind         


        
6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-01 00:47

    In my case, a certain HTTP Request would work in curl within Git Bash on Windows. However, I would get a Connection Reset error when running on Java using HttpClient and HttpGet (org.apache.http.client.methods.HttpGet).

    If I tried to use exec to directly run the command, for some reason it would not work.

    As a workaround, this code will write the command in a batch file, then run the batch file and place the output in command.txt.

    Here is the command which needs to be in the command.bat file (I have changed the endpoint and password):

    "C:\Users\scottizu\AppData\Local\Programs\Git\bin\sh.exe" --login -i -c "curl 'https://my.server.com/validate/user/scottizu' -H 'Password: MY_PASSWORD' > command.txt"
    

    Here is the code (notice the command has special characters escaped):

    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileWriter;
    
    public class CURL_Runner {
        public static void main (String[] args) throws Exception {
            String command = "\"C:\\Users\\scottizu\\AppData\\Local\\Programs\\Git\\bin\\sh.exe\" --login -i -c \"curl 'https://my.server.com/validate/user/scottizu' -H 'Password: MY_PASSWORD' > command.txt\"";
            createAndExecuteBatchFile(command);
        }
    
        public static void createAndExecuteBatchFile(String command) throws Exception {
    
            // Step 1: Write command in command.bat
            File fileToUpload = new File("C:\\command.bat");
            try {
                if(fileToUpload.getParentFile() != null && !fileToUpload.exists()) {
                    fileToUpload.getParentFile().mkdirs();
                }
                FileWriter fw = new FileWriter(fileToUpload);
                BufferedWriter bw = new BufferedWriter(fw);
                bw.write(command);
                bw.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            // Step 2: Execute command.bat
            String[] cmdArray = new String[1];
            cmdArray[0] = "C:\\command.bat";
    
            Process process = Runtime.getRuntime().exec(cmdArray, null, new File("C:\\"));
            int processComplete = process.waitFor();
        }
    }
    

提交回复
热议问题