1 linux和windows分隔符不一致问题解决java
File.separator经过这个函数能够获取对应windows和linux的分隔符linux
windows:E:\\jenkins\\workspace\\shell
"E:"+File.separator+"jenkins"+File.separator+"workspace"+File.separatorwindows
linux:/var/lib/jenkins/workspace/bash
File.separator+"var"+File.separator+"lib"+File.separator+"jenkins"+File.separator+"workspace"函数
2判断当前系统的类型spa
String osname = System.getProperty("os.name");
if ((osname != null) && (osname.toLowerCase().startsWith("win"))){
//win操做系统
return 1;
}
//linux操做系统
return 0;
}操作系统
3获取项目当前路径get
//File directory = new File("test-data/pp/");jenkins
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:\test\bin,CurPath的值为E:\test\bin\
SET CurPath=%CurPath:~0,-1% 获取变量1到n-1对应的字段,去除了最后的分割符号
linux下shell脚本
workdir=$(cd $(dirname $0); pwd) 获取到当前目录
链接字符能够直接用变量加上引号,例如变量param的值是/bin/bash,则${param}'/'的值为/bin/bash/