• 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/

  • 相关阅读:
    北京 到 娄底 灌湄
    AVR--IO设置编程
    AVR--I/O端口寄存器
    AVR--IO结构分析
    虚拟机VM下 UBUNTU 下安装Mantis
    Windows环境下Mantis搭建概述
    SW4STM32 : Error message from debugger back end: Error erasing flash with vFlashErase packet Error erasing flash with vFlashErase packet
    三极管驱动继电器详解
    STM32 Bootloader 跳转到App
    (转载) STM32IAP升级---IAP升级功能编写初期的一些困惑与疑问---完成功能后的总结
  • 原文地址:https://www.cnblogs.com/meadow/p/9089540.html
Copyright © 2020-2023  润新知