- 先把文件转码,使用linux命令dos2unix filename(文件名),直接把文件转换为unix格式,因为windows 下的换行符是 \r\n,而 linux 下的换行符是 \n
- 给文件授权,linux命令:/bin/chmod 755 filename(文件名)
- 调式shell,Windows下使用:cmd /c,linux下使用:sh
判断程序当前运行环境,根据环境不同执行不同命令
//判断当前运行环境
public static boolean getIsWindows() {
return System.getProperty("os.name").toLowerCase().startsWith("windows");
}
调用shell脚本
try {
ProcessBuilder b;
//windows跟Linux环境执行命令不一样
if (getIsWindows()) {
b = new ProcessBuilder("cmd", "/c", "脚本名", "参数1",
"参数2");
} else {
b = new ProcessBuilder("sh", "脚本名", "参数1",
"参数2");
}
b.directory(new File("脚本路径"));
Process rt = b.start();
int status = rt.waitFor();//获取shell返回结果
//判断shell执行是否成功
if (status != 0) {
log.error("shell执行异常:{}", getResult(rt.getErrorStream()));
}
} catch (Exception e) {
e.printStackTrace();
}
获取脚本返回结果
//获取脚本返回结果
public static String getResult(InputStream stream) {
BufferedReader br = null;
try {
String charsetName = getIsWindows() ? "GB2312" : "UTF-8";
br = new BufferedReader(new InputStreamReader(stream, charsetName));
String line;
StringBuilder sb = new StringBuilder();
while (null != (line = br.readLine())) {
sb.append(line).append("\n");
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
复制文件脚本,通过递归方式
#!/bin/bash
function recursive_copy_file(){
dirlist=$(ls $1)
for name in ${dirlist[*]}
do
if [ -f $1/$name ]; then
# 如果是文件,并且$2不存在该文件,则直接copy
if [ ! -f $2/$name ]; then
cp $1/$name $2/$name
curl -X GET "localhost:8082/index/shellPushProgress?fileType=1&fileName="+$name -H "accept: */*"
fi
elif [ -d $1/$name ]; then
# 如果是目录,并且$2不存在该目录,则先创建目录
if [ ! -d $2/$name ]; then
mkdir -p $2/$name
curl -X GET "localhost:8082/index/shellPushProgress?fileType=2&fileName="+$name -H "accept: */*"
fi
# 递归拷贝
recursive_copy_file $1/$name $2/$name
fi
done
}
echo $1
echo $2
source_dir=$1
dest_dir=$2
recursive_copy_file $source_dir $dest_dir
#echo "执行完成";
#read -p "press enter end"
#read -p "press enter end"