zoukankan      html  css  js  c++  java
  • java 执行shell脚本

    1 linux和windows分隔符不一致问题解决

    File.separator通过这个函数可以获取对应windows和linux的分隔符

    windows:E:\jenkins\workspace\

    "E:"+File.separator+"jenkins"+File.separator+"workspace"+File.separator

    linux:/var/lib/jenkins/workspace/

    File.separator+"var"+File.separator+"lib"+File.separator+"jenkins"+File.separator+"workspace"

    2判断当前系统的类型

    String osname = System.getProperty("os.name");
    if ((osname != null) && (osname.toLowerCase().startsWith("win"))){
    //win操作系统
    return 1;
    }
    //linux操作系统
    return 0;
    }

    3获取项目当前路径

    //File directory = new File("test-data/pp/");

    File directory = new File("test-data" + File.separator + "pp" + File.separator);
    String courseFile = directory.getCanonicalPath();

    4 java执行shell命令,由于执行的shell脚本需要权限,在执行shell脚本前先调用shell命令修改对应的权限,然后执行shell脚本

    List<String> commandList = new LinkedList<String>();

    commandList.add("test.sh");
    commandList.add("fileparam");

    //组装命令

    String[] commands = new String[commandList.size()];
    for (int i = 0; i < commandList.size(); i++) {
    commands[i] = commandList.get(i);
    }

    执行shell命令

    process = Runtime.getRuntime().exec(commands);

    可以参考https://www.jianshu.com/p/af4b3264bc5d

    5 遇个文件找不到或者打不开,权限不够的情况,修改权限,还有error 2,no such file等,可能是shell脚本中有java识别不了的字符,可以用echo $SHELL命令可以查看当前系统使用的shell类型和路径,例如/bin/bash

    List<String> commandList0 = new LinkedList<String>();
    commandList0.add("/bin/bash");
    commandList0.add("-c");
    commandList0.add("chmod -R 777 " + courseFile);

    6  windows和linux用的脚本不一样,编写一个.bat和一个.sh

    windows下bat文件中 设置变量:

    SET ttt=%1   将第一个参数赋值给变量ttt

    SET CurPath=%~dp0   获取到当前路径,例如文件位于目录下E: estin,CurPath的值为E: estin

    SET CurPath=%CurPath:~0,-1%   获取变量1到n-1对应的字段,去除了最后的分割符号

    linux下shell脚本

    workdir=$(cd $(dirname $0); pwd)  获取到当前目录

    连接字符可以直接用变量加上引号,例如变量param的值是/bin/bash,则${param}'/'的值为/bin/bash/

  • 相关阅读:
    【原创】禁止快播自动升级到最新版本,自己发现的方法
    又一灵异事件 Delphi 2007 在 Win7
    [DCC Error] E2161 Error: RLINK32: Error opening file "_____.drf"
    单例模式 改进
    estackoverflow with message 'stack overflow'
    所有可选的快捷键列表[转自万一博客]
    SQL server 除法运算
    正则表达式的一个坑[.\n]无效引起的血案
    getcwd()和__DIR__区别
    并发处理的技巧php
  • 原文地址:https://www.cnblogs.com/meadow/p/9089540.html
Copyright © 2011-2022 走看看