powershell-shell-detection

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

PowerShell Shell Detection & Cross-Shell Compatibility

PowerShell Shell检测与跨Shell兼容性

Critical guidance for distinguishing between PowerShell and Git Bash/MSYS2 shells on Windows, with shell-specific path handling and compatibility notes.
本文提供Windows系统下区分PowerShell与Git Bash/MSYS2 Shell的重要指南,包含Shell专属路径处理方法及兼容性说明。

Shell Detection Priority (Windows)

Windows系统下的Shell检测优先级

When working on Windows, correctly identifying the shell environment is crucial for proper path handling and command execution.
在Windows系统中工作时,正确识别Shell环境对路径处理和命令执行至关重要。

Detection Order (Most Reliable First)

检测顺序(可靠性从高到低)

  1. process.env.PSModulePath (PowerShell specific)
  2. process.env.MSYSTEM (Git Bash/MinGW specific)
  3. process.env.WSL_DISTRO_NAME (WSL specific)
  4. uname -s output (Cross-shell, requires execution)
  1. process.env.PSModulePath(PowerShell专属)
  2. process.env.MSYSTEM(Git Bash/MinGW专属)
  3. process.env.WSL_DISTRO_NAME(WSL专属)
  4. uname -s输出(跨Shell,需执行命令)

PowerShell Detection

PowerShell检测

Primary Indicators

主要识别指标

PSModulePath (Most Reliable):
powershell
undefined
PSModulePath(最可靠):
powershell
undefined

PowerShell detection

PowerShell detection

if ($env:PSModulePath) { Write-Host "Running in PowerShell" # PSModulePath contains 3+ paths separated by semicolons $env:PSModulePath -split ';' }
if ($env:PSModulePath) { Write-Host "Running in PowerShell" # PSModulePath contains 3+ paths separated by semicolons $env:PSModulePath -split ';' }

Check PowerShell version

Check PowerShell version

$PSVersionTable.PSVersion
$PSVersionTable.PSVersion

Output: 7.5.4 (PowerShell 7) or 5.1.x (Windows PowerShell)

Output: 7.5.4 (PowerShell 7) or 5.1.x (Windows PowerShell)


**PowerShell-Specific Variables:**
```powershell

**PowerShell专属变量:**
```powershell

These only exist in PowerShell

These only exist in PowerShell

$PSVersionTable # Version info $PSScriptRoot # Script directory $PSCommandPath # Script full path $IsWindows # Platform detection (PS 7+) $IsLinux # Platform detection (PS 7+) $IsMacOS # Platform detection (PS 7+)
undefined
$PSVersionTable # Version info $PSScriptRoot # Script directory $PSCommandPath # Script full path $IsWindows # Platform detection (PS 7+) $IsLinux # Platform detection (PS 7+) $IsMacOS # Platform detection (PS 7+)
undefined

Shell Type Detection in Scripts

脚本中的Shell类型检测

powershell
function Get-ShellType {
    if ($PSVersionTable) {
        return "PowerShell $($PSVersionTable.PSVersion)"
    }
    elseif ($env:PSModulePath -and ($env:PSModulePath -split ';').Count -ge 3) {
        return "PowerShell (detected via PSModulePath)"
    }
    else {
        return "Not PowerShell"
    }
}

Get-ShellType
powershell
function Get-ShellType {
    if ($PSVersionTable) {
        return "PowerShell $($PSVersionTable.PSVersion)"
    }
    elseif ($env:PSModulePath -and ($env:PSModulePath -split ';').Count -ge 3) {
        return "PowerShell (detected via PSModulePath)"
    }
    else {
        return "Not PowerShell"
    }
}

Get-ShellType

Git Bash / MSYS2 Detection

Git Bash / MSYS2检测

Primary Indicators

主要识别指标

MSYSTEM Environment Variable (Most Reliable):
bash
undefined
MSYSTEM环境变量(最可靠):
bash
undefined

Bash detection in Git Bash/MSYS2

Bash detection in Git Bash/MSYS2

if [ -n "$MSYSTEM" ]; then echo "Running in Git Bash/MSYS2: $MSYSTEM" fi
if [ -n "$MSYSTEM" ]; then echo "Running in Git Bash/MSYS2: $MSYSTEM" fi

MSYSTEM values:

MSYSTEM values:

MINGW64 - Native Windows 64-bit environment

MINGW64 - Native Windows 64-bit environment

MINGW32 - Native Windows 32-bit environment

MINGW32 - Native Windows 32-bit environment

MSYS - POSIX-compliant build environment

MSYS - POSIX-compliant build environment


**Secondary Detection Methods:**
```bash

**次要检测方法:**
```bash

Using OSTYPE (Bash-specific)

Using OSTYPE (Bash-specific)

case "$OSTYPE" in msys*) echo "MSYS/Git Bash" ;; cygwin*) echo "Cygwin" ;; linux*) echo "Linux" ;; darwin*) echo "macOS" ;; esac
case "$OSTYPE" in msys*) echo "MSYS/Git Bash" ;; cygwin*) echo "Cygwin" ;; linux*) echo "Linux" ;; darwin*) echo "macOS" ;; esac

Using uname (Most portable)

Using uname (Most portable)

case "$(uname -s)" in MINGW64*) echo "Git Bash 64-bit" ;; MINGW32*) echo "Git Bash 32-bit" ;; MSYS*) echo "MSYS" ;; CYGWIN*) echo "Cygwin" ;; Linux*) echo "Linux" ;; Darwin*) echo "macOS" ;; esac
undefined
case "$(uname -s)" in MINGW64*) echo "Git Bash 64-bit" ;; MINGW32*) echo "Git Bash 32-bit" ;; MSYS*) echo "MSYS" ;; CYGWIN*) echo "Cygwin" ;; Linux*) echo "Linux" ;; Darwin*) echo "macOS" ;; esac
undefined

Cross-Shell Compatibility on Windows

Windows系统下的跨Shell兼容性

Critical Differences

关键差异

AspectPowerShellGit Bash/MSYS2
Environment Variable
$env:VARIABLE
$VARIABLE
Path Separator
;
(semicolon)
:
(colon)
Path Style
C:\Windows\System32
/c/Windows/System32
Home Directory
$env:USERPROFILE
$HOME
Temp Directory
$env:TEMP
/tmp
Command Format
Get-ChildItem
ls
(native command)
AliasesPowerShell cmdlet aliasesUnix command aliases
方面PowerShellGit Bash/MSYS2
环境变量
$env:VARIABLE
$VARIABLE
路径分隔符
;
(分号)
:
(冒号)
路径格式
C:\Windows\System32
/c/Windows/System32
主目录
$env:USERPROFILE
$HOME
临时目录
$env:TEMP
/tmp
命令格式
Get-ChildItem
ls
(原生命令)
别名PowerShell cmdlet别名Unix命令别名

Path Handling: PowerShell vs Git Bash

路径处理:PowerShell vs Git Bash

PowerShell Path Handling:
powershell
undefined
PowerShell路径处理:
powershell
undefined

Native Windows paths work directly

Native Windows paths work directly

$path = "C:\Users\John\Documents" Test-Path $path # True
$path = "C:\Users\John\Documents" Test-Path $path # True

Forward slashes also work in PowerShell 7+

Forward slashes also work in PowerShell 7+

$path = "C:/Users/John/Documents" Test-Path $path # True
$path = "C:/Users/John/Documents" Test-Path $path # True

Use Join-Path for cross-platform compatibility

Use Join-Path for cross-platform compatibility

$configPath = Join-Path -Path $PSScriptRoot -ChildPath "config.json"
$configPath = Join-Path -Path $PSScriptRoot -ChildPath "config.json"

Use [System.IO.Path] for advanced scenarios

Use [System.IO.Path] for advanced scenarios

$fullPath = [System.IO.Path]::Combine($home, "documents", "file.txt")

**Git Bash Path Handling:**
```bash
$fullPath = [System.IO.Path]::Combine($home, "documents", "file.txt")

**Git Bash路径处理:**
```bash

Git Bash uses Unix-style paths

Git Bash uses Unix-style paths

path="/c/Users/John/Documents" test -d "$path" && echo "Directory exists"
path="/c/Users/John/Documents" test -d "$path" && echo "Directory exists"

Automatic path conversion (CAUTION)

Automatic path conversion (CAUTION)

Git Bash converts Unix-style paths to Windows-style

Git Bash converts Unix-style paths to Windows-style

/c/Users → C:\Users (automatic)

/c/Users → C:\Users (automatic)

Arguments starting with / may be converted unexpectedly

Arguments starting with / may be converted unexpectedly

Use cygpath for manual conversion

Use cygpath for manual conversion

cygpath -u "C:\path" # → /c/path (Unix format) cygpath -w "/c/path" # → C:\path (Windows format) cygpath -m "/c/path" # → C:/path (Mixed format)
undefined
cygpath -u "C:\path" # → /c/path (Unix format) cygpath -w "/c/path" # → C:\path (Windows format) cygpath -m "/c/path" # → C:/path (Mixed format)
undefined

Automatic Path Conversion in Git Bash (CRITICAL)

Git Bash中的自动路径转换(重点)

Git Bash/MSYS2 automatically converts paths in certain scenarios, which can cause issues:
Git Bash/MSYS2会在特定场景下自动转换路径,这可能引发问题:

What Triggers Conversion

触发转换的场景

bash
undefined
bash
undefined

Leading forward slash triggers conversion

Leading forward slash triggers conversion

command /foo # Converts to C:\msys64\foo
command /foo # Converts to C:\msys64\foo

Path lists with colons

Path lists with colons

export PATH=/foo:/bar # Converts to C:\msys64\foo;C:\msys64\bar
export PATH=/foo:/bar # Converts to C:\msys64\foo;C:\msys64\bar

Arguments after dashes

Arguments after dashes

command --path=/foo # Converts to --path=C:\msys64\foo
undefined
command --path=/foo # Converts to --path=C:\msys64\foo
undefined

What's Exempt from Conversion

不触发转换的场景

bash
undefined
bash
undefined

Arguments with equals sign (variable assignments)

Arguments with equals sign (variable assignments)

VAR=/foo command # NOT converted
VAR=/foo command # NOT converted

Drive specifiers

Drive specifiers

command C:/path # NOT converted
command C:/path # NOT converted

Arguments with semicolons (already Windows format)

Arguments with semicolons (already Windows format)

command "C:\foo;D:\bar" # NOT converted
command "C:\foo;D:\bar" # NOT converted

Double slashes (Windows switches)

Double slashes (Windows switches)

command //e //s # NOT converted
undefined
command //e //s # NOT converted
undefined

Disabling Path Conversion

禁用路径转换

bash
undefined
bash
undefined

Disable ALL conversion (Git Bash)

Disable ALL conversion (Git Bash)

export MSYS_NO_PATHCONV=1 command /foo # Stays as /foo
export MSYS_NO_PATHCONV=1 command /foo # Stays as /foo

Exclude specific patterns (MSYS2)

Exclude specific patterns (MSYS2)

export MSYS2_ARG_CONV_EXCL="*" # Exclude everything export MSYS2_ARG_CONV_EXCL="--dir=;/test" # Specific prefixes
undefined
export MSYS2_ARG_CONV_EXCL="*" # Exclude everything export MSYS2_ARG_CONV_EXCL="--dir=;/test" # Specific prefixes
undefined

When to Use PowerShell vs Git Bash on Windows

Windows系统下何时使用PowerShell vs Git Bash

Use PowerShell When:

优先使用PowerShell的场景:

  • Windows-specific tasks - Registry, WMI, Windows services
  • Azure/Microsoft 365 automation - Az, Microsoft.Graph modules
  • Module ecosystem - Leverage PSGallery modules
  • Object-oriented pipelines - Rich object manipulation
  • Native Windows integration - Built into Windows
  • CI/CD with pwsh - GitHub Actions, Azure DevOps
  • Cross-platform scripting - PowerShell 7 works on Linux/macOS
Example PowerShell Scenario:
powershell
undefined
  • Windows专属任务 - 注册表、WMI、Windows服务管理
  • Azure/Microsoft 365自动化 - Az、Microsoft.Graph模块
  • 模块生态系统 - 利用PSGallery模块
  • 面向对象管道 - 丰富的对象操作能力
  • 原生Windows集成 - 系统内置工具
  • 基于pwsh的CI/CD - GitHub Actions、Azure DevOps
  • 跨平台脚本编写 - PowerShell 7支持Linux/macOS
PowerShell示例场景:
powershell
undefined

Azure VM management with Az module

Azure VM management with Az module

Connect-AzAccount Get-AzVM -ResourceGroupName "Production" | Where-Object {$_.PowerState -eq "VM running"} | Stop-AzVM -Force
undefined
Connect-AzAccount Get-AzVM -ResourceGroupName "Production" | Where-Object {$_.PowerState -eq "VM running"} | Stop-AzVM -Force
undefined

Use Git Bash When:

优先使用Git Bash的场景:

  • Unix tool compatibility - sed, awk, grep, find
  • Git operations - Native Git command-line experience
  • POSIX script execution - Running Linux shell scripts
  • Cross-platform shell scripts - Bash scripts from Linux/macOS
  • Text processing - Unix text utilities (sed, awk, cut)
  • Development workflows - Node.js, Python, Ruby with Unix tools
Example Git Bash Scenario:
bash
undefined
  • Unix工具兼容性 - sed、awk、grep、find
  • Git操作 - 原生Git命令行体验
  • POSIX脚本执行 - 运行Linux Shell脚本
  • 跨平台Shell脚本 - 来自Linux/macOS的Bash脚本
  • 文本处理 - Unix文本工具(sed、awk、cut)
  • 开发工作流 - Node.js、Python、Ruby搭配Unix工具
Git Bash示例场景:
bash
undefined

Git workflow with Unix tools

Git workflow with Unix tools

git log --oneline | grep -i "feature" | awk '{print $1}' | xargs git show --stat
undefined
git log --oneline | grep -i "feature" | awk '{print $1}' | xargs git show --stat
undefined

Shell-Aware Script Design

感知Shell类型的脚本设计

Detect and Adapt (PowerShell)

检测与适配(PowerShell)

powershell
undefined
powershell
undefined

Detect if running in PowerShell or Git Bash context

Detect if running in PowerShell or Git Bash context

function Test-PowerShellContext { return ($null -ne $PSVersionTable) }
function Test-PowerShellContext { return ($null -ne $PSVersionTable) }

Adapt path handling based on context

Adapt path handling based on context

function Get-CrossPlatformPath { param([string]$Path)
if (Test-PowerShellContext) {
    # PowerShell: Use Join-Path
    return (Resolve-Path $Path -ErrorAction SilentlyContinue).Path
}
else {
    # Non-PowerShell context
    Write-Warning "Not running in PowerShell. Path operations may differ."
    return $Path
}
}
undefined
function Get-CrossPlatformPath { param([string]$Path)
if (Test-PowerShellContext) {
    # PowerShell: Use Join-Path
    return (Resolve-Path $Path -ErrorAction SilentlyContinue).Path
}
else {
    # Non-PowerShell context
    Write-Warning "Not running in PowerShell. Path operations may differ."
    return $Path
}
}
undefined

Detect and Adapt (Bash)

检测与适配(Bash)

bash
undefined
bash
undefined

Detect shell environment

Detect shell environment

detect_shell() { if [ -n "$MSYSTEM" ]; then echo "git-bash" elif [ -n "$PSModulePath" ]; then echo "powershell" elif [ -n "$WSL_DISTRO_NAME" ]; then echo "wsl" else echo "unix" fi }
detect_shell() { if [ -n "$MSYSTEM" ]; then echo "git-bash" elif [ -n "$PSModulePath" ]; then echo "powershell" elif [ -n "$WSL_DISTRO_NAME" ]; then echo "wsl" else echo "unix" fi }

Adapt path handling

Adapt path handling

convert_path() { local path="$1" local shell_type=$(detect_shell)
case "$shell_type" in
    git-bash)
        # Convert Windows path to Unix style
        echo "$path" | sed 's|\\|/|g' | sed 's|^\([A-Z]\):|/\L\1|'
        ;;
    *)
        echo "$path"
        ;;
esac
}
convert_path() { local path="$1" local shell_type=$(detect_shell)
case "$shell_type" in
    git-bash)
        # Convert Windows path to Unix style
        echo "$path" | sed 's|\\|/|g' | sed 's|^\([A-Z]\):|/\L\1|'
        ;;
    *)
        echo "$path"
        ;;
esac
}

Usage

Usage

shell_type=$(detect_shell) echo "Running in: $shell_type"
undefined
shell_type=$(detect_shell) echo "Running in: $shell_type"
undefined

Environment Variable Comparison

环境变量对比

Common Environment Variables

常见环境变量

VariablePowerShellGit BashPurpose
Username
$env:USERNAME
$USER
Current user
Home Directory
$env:USERPROFILE
$HOME
User home
Temp Directory
$env:TEMP
/tmp
Temporary files
Path List
$env:Path
(
;
sep)
$PATH
(
:
sep)
Executable paths
Shell Detection
$env:PSModulePath
$MSYSTEM
Shell identifier
变量PowerShellGit Bash用途
Username
$env:USERNAME
$USER
当前用户
主目录
$env:USERPROFILE
$HOME
用户主目录
临时目录
$env:TEMP
/tmp
临时文件存储
路径列表
$env:Path
;
分隔)
$PATH
:
分隔)
可执行文件路径
Shell检测
$env:PSModulePath
$MSYSTEM
Shell识别标识

Cross-Shell Variable Access

跨Shell变量访问

PowerShell accessing environment variables:
powershell
$env:PATH              # Current PATH
$env:PSModulePath      # PowerShell module paths
$env:MSYSTEM           # Would be empty in PowerShell
[Environment]::GetEnvironmentVariable("PATH", "Machine")  # System PATH
Git Bash accessing environment variables:
bash
echo $PATH             # Current PATH
echo $MSYSTEM          # Git Bash: MINGW64, MINGW32, or MSYS
echo $PSModulePath     # Would be empty in pure Bash
PowerShell访问环境变量:
powershell
$env:PATH              # Current PATH
$env:PSModulePath      # PowerShell module paths
$env:MSYSTEM           # Would be empty in PowerShell
[Environment]::GetEnvironmentVariable("PATH", "Machine")  # System PATH
Git Bash访问环境变量:
bash
echo $PATH             # Current PATH
echo $MSYSTEM          # Git Bash: MINGW64, MINGW32, or MSYS
echo $PSModulePath     # Would be empty in pure Bash

Practical Examples

实用示例

Example 1: Cross-Shell File Finding

示例1:跨Shell文件查找

PowerShell:
powershell
undefined
PowerShell:
powershell
undefined

Find files modified in last 7 days

Find files modified in last 7 days

Get-ChildItem -Path "C:\Projects" -Recurse -File | Where-Object { $_.LastWriteTime -gt (Get-Date).AddDays(-7) } | Select-Object FullName, LastWriteTime

**Git Bash:**
```bash
Get-ChildItem -Path "C:\Projects" -Recurse -File | Where-Object { $_.LastWriteTime -gt (Get-Date).AddDays(-7) } | Select-Object FullName, LastWriteTime

**Git Bash:**
```bash

Same operation in Git Bash

Same operation in Git Bash

find /c/Projects -type f -mtime -7 -exec ls -lh {} ;
undefined
find /c/Projects -type f -mtime -7 -exec ls -lh {} ;
undefined

Example 2: Process Management

示例2:进程管理

PowerShell:
powershell
undefined
PowerShell:
powershell
undefined

Stop all Chrome processes

Stop all Chrome processes

Get-Process chrome -ErrorAction SilentlyContinue | Stop-Process -Force

**Git Bash:**
```bash
Get-Process chrome -ErrorAction SilentlyContinue | Stop-Process -Force

**Git Bash:**
```bash

Same operation in Git Bash

Same operation in Git Bash

ps aux | grep chrome | awk '{print $2}' | xargs kill -9 2>/dev/null
undefined
ps aux | grep chrome | awk '{print $2}' | xargs kill -9 2>/dev/null
undefined

Example 3: Text File Processing

示例3:文本文件处理

PowerShell:
powershell
undefined
PowerShell:
powershell
undefined

Extract unique email addresses from logs

Extract unique email addresses from logs

Get-Content "logs.txt" | Select-String -Pattern '\b[A-Za-z0-9.%+-]+@[A-Za-z0-9.-]+.[A-Z|a-z]{2,}\b' | ForEach-Object { $.Matches.Value } | Sort-Object -Unique

**Git Bash:**
```bash
Get-Content "logs.txt" | Select-String -Pattern '\b[A-Za-z0-9.%+-]+@[A-Za-z0-9.-]+.[A-Z|a-z]{2,}\b' | ForEach-Object { $.Matches.Value } | Sort-Object -Unique

**Git Bash:**
```bash

Same operation in Git Bash

Same operation in Git Bash

grep -oE '\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Z|a-z]{2,}\b' logs.txt | sort -u
undefined
grep -oE '\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Z|a-z]{2,}\b' logs.txt | sort -u
undefined

Troubleshooting Cross-Shell Issues

跨Shell问题排查

Issue 1: Command Not Found

问题1:命令未找到

Problem: Command works in one shell but not another
powershell
undefined
问题: 命令在一个Shell中可用,但在另一个中不可用
powershell
undefined

PowerShell

PowerShell

Get-Process # Works
```bash
Get-Process # 可用
```bash

Git Bash

Git Bash

Get-Process # Command not found

**Solution:** Understand that PowerShell cmdlets don't exist in Bash. Use native commands or install PowerShell Core (pwsh) in Git Bash:
```bash
Get-Process # 命令未找到

**解决方案:** 了解PowerShell cmdlet在Bash中不存在。使用原生命令或在Git Bash中安装PowerShell Core(pwsh):
```bash

Run PowerShell from Git Bash

Run PowerShell from Git Bash

pwsh -Command "Get-Process"
undefined
pwsh -Command "Get-Process"
undefined

Issue 2: Path Format Mismatches

问题2:路径格式不匹配

Problem: Paths don't work across shells
bash
undefined
问题: 路径在不同Shell中无法正常工作
bash
undefined

Git Bash path

Git Bash路径

/c/Users/John/file.txt # Works in Bash
/c/Users/John/file.txt # 在Bash中可用

PowerShell

PowerShell

Test-Path "/c/Users/John/file.txt" # May fail

**Solution:** Use cygpath for conversion or normalize paths:
```bash
Test-Path "/c/Users/John/file.txt" # 可能失败

**解决方案:** 使用cygpath进行转换或标准化路径:
```bash

Convert to Windows format for PowerShell

Convert to Windows format for PowerShell

win_path=$(cygpath -w "/c/Users/John/file.txt") pwsh -Command "Test-Path '$win_path'"
undefined
win_path=$(cygpath -w "/c/Users/John/file.txt") pwsh -Command "Test-Path '$win_path'"
undefined

Issue 3: Alias Conflicts

问题3:别名冲突

Problem:
ls
,
cd
,
cat
behave differently
powershell
undefined
问题:
ls
cd
cat
的行为不同
powershell
undefined

PowerShell

PowerShell

ls # Actually runs Get-ChildItem
```bash
ls # 实际执行Get-ChildItem
```bash

Git Bash

Git Bash

ls # Runs native Unix ls command

**Solution:** Use full cmdlet names in PowerShell scripts:
```powershell
ls # 执行原生Unix ls命令

**解决方案:** 在PowerShell脚本中使用完整cmdlet名称:
```powershell

Instead of: ls

Instead of: ls

Get-ChildItem # Explicit cmdlet name
undefined
Get-ChildItem # 明确cmdlet名称
undefined

Best Practices Summary

最佳实践总结

PowerShell Scripts

PowerShell脚本

  1. ✅ Use
    $PSScriptRoot
    for script-relative paths
  2. ✅ Use
    Join-Path
    or
    [IO.Path]::Combine()
    for paths
  3. ✅ Avoid hardcoded backslashes
  4. ✅ Use full cmdlet names (no aliases)
  5. ✅ Test on all target platforms
  6. ✅ Use
    $IsWindows
    ,
    $IsLinux
    ,
    $IsMacOS
    for platform detection
  1. ✅ 使用
    $PSScriptRoot
    获取脚本相对路径
  2. ✅ 使用
    Join-Path
    [IO.Path]::Combine()
    处理路径
  3. ✅ 避免硬编码反斜杠
  4. ✅ 使用完整cmdlet名称(不使用别名)
  5. ✅ 在所有目标平台上测试
  6. ✅ 使用
    $IsWindows
    $IsLinux
    $IsMacOS
    进行平台检测

Git Bash Scripts

Git Bash脚本

  1. ✅ Check
    $MSYSTEM
    for Git Bash detection
  2. ✅ Use
    cygpath
    for path conversion when needed
  3. ✅ Set
    MSYS_NO_PATHCONV=1
    to disable auto-conversion if needed
  4. ✅ Quote paths with spaces
  5. ✅ Use Unix-style paths (
    /c/...
    ) within Bash
  6. ✅ Convert to Windows paths when calling Windows tools
  1. ✅ 检查
    $MSYSTEM
    以检测Git Bash
  2. ✅ 必要时使用
    cygpath
    进行路径转换
  3. ✅ 若需要,设置
    MSYS_NO_PATHCONV=1
    禁用自动转换
  4. ✅ 为包含空格的路径添加引号
  5. ✅ 在Bash中使用Unix格式路径(
    /c/...
  6. ✅ 调用Windows工具时转换为Windows格式路径

Cross-Shell Development

跨Shell开发

  1. ✅ Document which shell your script requires
  2. ✅ Add shell detection at script start
  3. ✅ Provide clear error messages for wrong shell
  4. ✅ Consider creating wrapper scripts for cross-shell compatibility
  5. ✅ Test in both PowerShell and Git Bash if supporting both
  1. ✅ 记录脚本所需的Shell环境
  2. ✅ 在脚本开头添加Shell检测逻辑
  3. ✅ 为错误Shell环境提供清晰的错误信息
  4. ✅ 考虑创建包装脚本以实现跨Shell兼容性
  5. ✅ 若支持两种Shell,需在PowerShell和Git Bash中都进行测试

Resources

参考资源