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/

  • 相关阅读:
    看懂SqlServer查询计划
    jQuery 插件autocomplete自动完成应用(自动补全)(asp.net后台)
    MVC Html.AntiForgeryToken() 防止CSRF攻击
    iOS开发UI篇—transframe属性(形变)
    iOS开发UI基础—手写控件,frame,center和bounds属性
    iOS开发UI篇—Button基础
    iOS开发UI篇—UITableviewcell的性能优化和缓存机制
    iOS开发UI篇—UITableview控件基本使用
    iOS开发UI篇—UITableview控件简单介绍
    iOS开发UI篇—推荐两个好用的Xcode插件(提供下载链接)
  • 原文地址:https://www.cnblogs.com/meadow/p/9089540.html
Copyright © 2011-2022 走看看