Jenkins 为我运行命令

发布: (2026年2月6日 GMT+8 08:06)
3 min read
原文: Dev.to

Source: Dev.to

Jenkins 之前

  • 工程师手动运行命令
  • 忘记步骤
  • 出错
  • 无法可靠地重复

使用 Jenkins 后

  • 命令只写一次
  • Jenkins 每次以相同方式运行它们
  • 任何人都可以点击 Build Now

🛠 任务规则(重要)

  • ❌ 不要复制‑粘贴
  • ✅ 学生必须逐行输入
  • ✅ 每输入一行后,解释它的作用

🧩 步骤 1:创建 Freestyle Job

  1. 打开 Jenkins
  2. 点击 New Item
  3. Job name: devops-first-script
  4. 选择 Freestyle project
  5. 点击 OK

🧩 步骤 2:添加 Shell 构建步骤

  1. 滚动到 Build
  2. 点击 Add build step
  3. 选择 Execute shell

✍️ 步骤 3:逐行编写以下脚本

# Line 1: simple output
echo "Hello from Jenkins"
# echo prints text – proves Jenkins can execute commands

# Validation: who am I?
whoami
# Shows which user Jenkins runs as – important for permissions

# Show current directory
pwd
# Shows where Jenkins runs (workspace), not your home folder

# List workspace contents
ls
# Workspace starts empty – useful before cloning repos

# Create a file
echo "This file was created by Jenkins" > jenkins.txt
# Demonstrates that Jenkins can create artifacts

# Display the file
cat jenkins.txt
# Confirms the file exists and its content

# Final log message
echo "Script completed successfully"
  • Explanation: Each command is typed to illustrate basic shell operations, verify the Jenkins environment, and produce an artifact (jenkins.txt). The final echo provides a clear log marker for successful completion.
  1. 点击 Save
  2. 点击 Build Now
  3. 打开 Console Output 查看结果

✅ 应该看到的内容

  • 打印的文本(Hello from Jenkins
  • 用户名(whoami 的输出)
  • Jenkins 工作区路径(pwd 的输出)
  • 确认已创建 jenkins.txt
  • 文件内容显示(cat jenkins.txt

概念

ConceptMeaning
Jenkins jobAutomation task
WorkspaceSafe execution directory
Shell stepReal Linux commands
LogsDebugging source
RepeatabilitySame result every time

必须的失败示例

exit 1
  • Question: “What do you think will happen?”
  • Result: The build turns RED. Jenkins stops; no further steps run.
  • Explanation: exit 1 signals failure. Jenkins trusts exit codes, which is why failing code can block deployments. This illustrates the principle: Jenkins is “stupid but honest.” It reflects real‑world DevOps behavior.
Back to Blog

相关文章

阅读更多 »