Jenkins Pipeline 中使用 sh
步骤来执行 Shell 脚本或命令。以下是一些示例,展示了如何在 Pipeline 中编写和使用 Shell 脚本的不同场景:
基础 Shell 命令执行
示例 1: 执行单条 Shell 命令
pipeline {
agent any
stages {
stage('Execute Shell Command') {
steps {
sh 'echo "Hello, World!"'
}
}
}
}
在这个例子中,Pipeline 执行了一个简单的 Shell 命令 echo "Hello, World!"
,输出问候语到控制台。
示例 2: 执行多条连续 Shell 命令
pipeline {
agent any
stages {
stage('Run Multiple Commands') {
steps {
sh '''
echo "Starting script execution..."
ls -l
echo "Script completed."
'''
}
}
}
}
此处使用了多行字符串(三引号包围),允许在单个 sh
步骤中编写多条 Shell 命令。这些命令会被当作一个整体在 Shell 环境中执行,顺序依次为打印消息、列出目录内容、再次打印消息。
命令返回值的捕获与处理
示例 3: 获取 Shell 命令的退出状态(返回值)
pipeline {
agent any
stages {
stage('Check Exit Status') {
steps {
script {
def result = sh(script: 'grep pattern non_existent_file', returnStatus: true)
if (result != 0) {
echo "Command failed with exit code ${result}"
} else {
echo "Command succeeded"
}
}
}
}
}
}
通过设置 returnStatus: true
,sh
步骤将返回 Shell 命令的退出状态(通常 0 表示成功,非零表示失败)。根据返回值,脚本可以做出相应的判断和处理。
环境变量与参数传递
示例 4: 使用环境变量和参数
pipeline {
agent any
parameters {
string(name: 'ENVIRONMENT', defaultValue: 'dev', description: 'Target environment')
}
stages {
stage('Deploy to Environment') {
steps {
sh """
echo "Deploying to ${params.ENVIRONMENT} environment..."
./deploy.sh --env=${params.ENVIRONMENT}
"""
}
}
}
}
此示例定义了一个 Pipeline 参数 ENVIRONMENT
,用户可以在触发构建时指定。Shell 脚本中引用了这个参数值,用于执行部署脚本 deploy.sh
,将应用程序部署到指定的环境。
工作空间操作
示例 5: 更改工作目录并执行命令
pipeline {
agent any
stages {
stage('Build in Specific Directory') {
steps {
dir('my_project') {
sh 'make build'
}
}
}
}
}
使用 dir
步骤可以临时切换工作目录。在此示例中,Pipeline 进入名为 my_project
的子目录,然后在那里执行 make build
命令。
管道输出的捕获与处理
示例 6: 捕获 Shell 命令的标准输出
pipeline {
agent any
stages {
stage('Capture Command Output') {
steps {
script {
def output = sh(script: 'ls -al', returnStdout: true)
echo "Output of ls command: ${output}"
}
}
}
}
}
设置 returnStdout: true
后,sh
步骤将返回 Shell 命令的标准输出作为字符串。这个输出可以被后续的 Groovy 代码处理,如在本例中将其打印到控制台。
以上示例展示了 Jenkins Pipeline 中使用 sh
步骤执行 Shell 脚本的各种常见场景。根据实际需求,您可以结合这些示例编写适合您项目的 Pipeline 脚本。