大家好,我是程序员柏风,AI 最全的 Vibecoding 学习地图 http://coderoadmap.cn 作者。
PowerShell vs Bash
同一任务在 PowerShell 与 Bash 上写法不同:前者管道传对象,后者管道传文本。CodeRoadMap 开发在 Windows(PowerShell),生产在 Linux(Bash)——两套都要会。
学习目标
- 对照常见运维任务的两种写法
- 判断何时用 PowerShell、何时用 Bash
- 与 linux-essentials 形成互补
核心内容
语法对照
| 任务 | Bash | PowerShell |
|---|---|---|
| 当前目录 | pwd | Get-Location |
| 列文件 | ls -la | Get-ChildItem -Force |
| 环境变量 | echo $PATH | $env:PATH |
| 管道过滤 | grep ERROR | Where-Object / Select-String |
| 条件 | if [ -f file ]; then | if (Test-Path file) { |
| 成功链 | cmd1 && cmd2 | cmd1; if ($?) { cmd2 } |
PowerShell 7+ 支持 && / ||,但旧版 5.1 不支持。
同一排查:端口与健康检查
# Bash(linux-shell)
ss -tlnp | grep -E '8080|3000'
curl -s http://127.0.0.1:8080/actuator/health
# PowerShell
Get-NetTCPConnection -LocalPort 8080,3000 -State Listen -ErrorAction SilentlyContinue
Invoke-RestMethod http://127.0.0.1:8080/actuator/health
Bash 用 curl + grep;PowerShell 原生 cmdlet 直接返回对象。
脚本扩展名与 shebang
| Bash | PowerShell | |
|---|---|---|
| 扩展名 | .sh | .ps1 |
| 首行 | #!/bin/bash | 无 shebang(或 #!/usr/bin/env pwsh) |
| 本站示例 | start-backend.sh | sync-courses.ps1 |
.bat 是 CMD 批处理(如 package-prod.bat),不是 PowerShell,但常与 .ps1 配合。
选型建议
- Windows 本地:课程同步、打 platform 包、查本机端口 → PowerShell
- Linux 服务器:Nginx、systemd、PM2、防火墙 → Bash(linux-deploy)
- CI:ubuntu-latest 跑 Bash;windows-latest 跑 PowerShell(gha-workflow)
- 容器:容器内通常是 Bash(docker-cli)
练习
- 用两种 Shell 各写一行:检查 8080 是否在监听
- 把
export API_BASE=...翻译成 PowerShell - 列出你日常只用 Windows 做的 3 件事、只用 Linux 做的 3 件事
小结
对象管道 vs 文本管道;Windows 脚本 vs 服务器 Shell——按环境选工具,不要混用语法。 下一课 Windows 部署 CodeRoadMap。