java设置linuxshell变量执行脚本


db.stop.sh

##db.stop.sh
su - sybase -c \"isql -Usa -P$SA_PWD -SlogDB\" << EOF
use master
go
checkpoint
go
shutdown SYB_BACKUP with nowait
go
shutdown with nowait
go
exit
EOF
sleep 60
echo "Database STOP done."


执行命令方法:

/**
	 * 执行本地命令并返回结果
	 * @param cmd 本地命令
	 * @param env 环境变量
	 * @param dir
	 * @return
	 * @throws IOException 
	 * @throws InterruptedException 
	 */
	static String exec(String cmd, String[] env, File dir) 
			throws IOException, InterruptedException{
		String res = "";
		int state = 0;
		byte[] buff = new byte[1024];
		int readLen = 0;
		InputStream stdIn = null;
		InputStream stdErr = null;
		
		try{			
			Runtime r = Runtime.getRuntime();
			Process p = r.exec(cmd, env, dir);			
			stdIn = p.getInputStream();
			stdErr = p.getErrorStream();
			state = p.waitFor();
			
			if(0==state){
				while(-1!=(readLen=stdIn.read(buff))){
					res = (new String(buff,0,readLen));
				}
				
				while(-1!=(readLen=stdErr.read(buff))){
					res = (new String(buff,0,readLen));
				}
			}else{
				res = "__ERROR__:"+state;
			}
		}finally{
			try{
				if(null!=stdIn) stdIn.close();
			}catch(Exception ex){				
			}
			
			try{
				if(null!=stdErr) stdErr.close();
			}catch(Exception ex){				
			}		
		}
		
		return res;
	}

测试类:

static void t5(){		
		try {
			String res = exec(
					"bash db.stop.sh", 
					new String[]{"SA_PWD=123456"}, 
					null);
			System.out.println(res);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}








你可能感兴趣的:(Java)