我基本上尝试建立到Linux机器的SSH连接,并在我的groovy脚本中执行shell命令,如下所示:
#!groovy
def serverName51 = "********"
def folderName = "tmp"
node('linux') {
def output = sh returnStdout: true, script:"ssh -q karthik@${serverName51} 'cd /tmp; mkdir ${folderName};'"
}
上面的代码返回一条错误消息,如下所示:
ERROR: script returned exit code 255
我知道shell脚本执行时会抛出一些错误。 如何在groovy中捕获并显示此错误?
所以你在这里向我们展示了一个执行shell脚本的dsl?
在DSL的内部,您必须创建一个Process对象。我直接使用java.lang.ProcessBuilder。
明确:
Process process=new ProcessBuilder().directory(workingDir).command(["sh", "ls -l"]).start()
Process
有几种方法可以让你获得shell命令的输出,以及退出代码:
/**
* Causes the current thread to wait, if necessary, until the
* subprocess represented by this {@code Process} object has
* terminated, or the specified waiting time elapses.
*
* <p>If the subprocess has already terminated then this method returns
* immediately with the value {@code true}. If the process has not
* terminated and the timeout value is less than, or equal to, zero, then
* this method returns immediately with the value {@code false}.
*
* <p>The default implementation of this methods polls the {@code exitValue}
* to check if the process has terminated. Concrete implementations of this
* class are strongly encouraged to override this method with a more
* efficient implementation.
*
* @param timeout the maximum time to wait
* @param unit the time unit of the {@code timeout} argument
* @return {@code true} if the subprocess has exited and {@code false} if
* the waiting time elapsed before the subprocess has exited.
* @throws InterruptedException if the current thread is interrupted
* while waiting.
* @throws NullPointerException if unit is null
* @since 1.8
*/
public boolean waitFor(long timeout, TimeUnit unit)
/**
* Causes the current thread to wait, if necessary, until the
* process represented by this {@code Process} object has
* terminated. This method returns immediately if the subprocess
* has already terminated. If the subprocess has not yet
* terminated, the calling thread will be blocked until the
* subprocess exits.
*
* @return the exit value of the subprocess represented by this
* {@code Process} object. By convention, the value
* {@code 0} indicates normal termination.
* @throws InterruptedException if the current thread is
* {@linkplain Thread#interrupt() interrupted} by another
* thread while it is waiting, then the wait is ended and
* an {@link InterruptedException} is thrown.
*/
public abstract int waitFor() throws InterruptedException;
/**
* Returns the exit value for the subprocess.
*
* @return the exit value of the subprocess represented by this
* {@code Process} object. By convention, the value
* {@code 0} indicates normal termination.
* @throws IllegalThreadStateException if the subprocess represented
* by this {@code Process} object has not yet terminated
*/
public abstract int exitValue();