How to fix Pipeline failed for branch main in Git

GitBEGINNERMEDIUMUpdated Dec 6, 2025· 155 views

This Bitbucket Pipelines error occurs when one or more steps in your CI/CD pipeline fail during execution. The failure can stem from test failures, build errors, configuration issues, or resource limits. To resolve it, examine the pipeline logs, identify the root cause, and fix the underlying issue in your code or configuration.

Quick fix

Fixes Pipeline failed for branch main

# Example log showing a test failure:
+ npm test

> my-app@1.0.0 test
> jest

FAIL  src/__tests__/utils.test.js
  ✕ should calculate correctly (5 ms)

Test Suites: 1 failed, 2 passed, 3 total
Tests:       1 failed, 8 passed, 9 total

error: command failed with exit code 1
  1. View the failed pipeline logs
  2. Verify your bitbucket-pipelines.yml configuration
  3. Reproduce the failure locally
  4. Fix test failures
git — error
# Example log showing a test failure:
+ npm test
> my-app@1.0.0 test
> jest
FAIL src/__tests__/utils.test.js
✕ should calculate correctly (5 ms)
Test Suites: 1 failed, 2 passed, 3 total
Tests: 1 failed, 8 passed, 9 total
error: command failed with exit code 1
Pipeline failed for branch main

What this error means

When you see "Pipeline failed for branch main" (or any other branch name), Bitbucket is telling you that your CI/CD pipeline did not complete successfully. A pipeline fails when any step returns a non-zero exit code, indicating an error. Bitbucket Pipelines runs the commands defined in your `bitbucket-pipelines.yml` file as bash/shell commands. The pipeline runner checks the exit status of each command - zero means success, non-zero means failure. When a step fails, subsequent steps are typically skipped unless configured otherwise. This error is Bitbucket's way of protecting your codebase and deployment targets from broken code. The failed pipeline prevents merging or deployment until the issue is resolved. Understanding why the pipeline failed requires examining the step logs, which show exactly what went wrong. Common categories of pipeline failures include: test failures, build compilation errors, linting violations, missing dependencies, environment variable issues, timeout errors, and memory exhaustion.

Typical symptoms

  • Bitbucket shows 'Pipeline #X failed' with red status indicator
  • Pull request shows 'Pipeline failed' and merge may be blocked
  • Email notification: 'Pipeline for branch X has failed'
  • Step shows red X with 'failed' status in pipeline view
  • Commit badge displays red failed state
  • Build logs show 'error: command failed with exit code X'
  • Subsequent steps show 'skipped' because earlier step failed
  • Repository settings show failed builds in Pipelines history
  • Deployment is blocked or rolled back due to failed pipeline

Common causes

  1. Test suite failures - unit tests, integration tests, or end-to-end tests not passing
  2. Build or compilation errors - code doesn't build successfully
  3. Linting or code style violations found by ESLint, Prettier, or similar tools
  4. YAML syntax errors or misconfiguration in bitbucket-pipelines.yml
  5. Missing dependencies - packages not installed or unavailable in CI environment
  6. Environment variables not set or configured incorrectly in repository settings
  7. Docker image not found or failed to pull from registry
  8. Memory limit exceeded (exit code 137) - build requires more RAM than allocated
  9. Build time limit exceeded - step took longer than allowed timeout
  10. Script command not found - missing binary or tool in build environment
  11. Permission denied errors - accessing files or services without proper access
  12. External service unavailable - API, database, or registry timeout
  13. Artifact processing errors - corrupted or missing build artifacts
  14. Git submodule clone failures - submodule URL inaccessible or misconfigured
  15. Piped commands masking errors - exit codes not properly captured

How to fix "Pipeline failed for branch main"

1View the failed pipeline logs

First, identify what caused the pipeline to fail by examining the logs:

1. Navigate to your repository in Bitbucket
2. Click on Pipelines in the left sidebar
3. Find the failed pipeline (marked with red X)
4. Click on the pipeline to see the steps
5. Click on the failed step to view its logs

text
# Example log showing a test failure:
+ npm test

> my-app@1.0.0 test
> jest

FAIL  src/__tests__/utils.test.js
  ✕ should calculate correctly (5 ms)

Test Suites: 1 failed, 2 passed, 3 total
Tests:       1 failed, 8 passed, 9 total

error: command failed with exit code 1

The key information is usually near the end of the log, right before the "command failed with exit code" message. Look for error messages, stack traces, or assertion failures.

2Verify your bitbucket-pipelines.yml configuration

Check your pipeline configuration file for common issues:

Ensure the file exists and is named correctly:
- File must be in the repository root
- Must use .yml extension (not .yaml)
- File name is case-sensitive: bitbucket-pipelines.yml

Validate YAML syntax:

yaml
# Correct structure:
image: node:18

pipelines:
  default:
    - step:
        name: Build and Test
        caches:
          - node
        script:
          - npm ci
          - npm test

  branches:
    main:
      - step:
          name: Deploy to Production
          script:
            - npm run deploy

Common configuration mistakes:

1. Missing step definition:

yaml
# Wrong - branches section needs step(s):
branches:
  main:
    - npm run deploy

# Correct:
branches:
  main:
    - step:
        script:
          - npm run deploy

2. Incorrect indentation (YAML is sensitive to spaces):

yaml
# Wrong - mixed indentation:
pipelines:
  default:
   - step:  # Only 1 space!
        script:
          - npm test

# Correct - consistent 2-space indentation:
pipelines:
  default:
    - step:
        script:
          - npm test

3. Branch-specific pipeline not in target branch:
If you commit bitbucket-pipelines.yml to main, only the main or default pipeline runs. For branch-specific pipelines to work, the file must exist in that branch.

3Reproduce the failure locally

Before making changes, try to reproduce the issue on your machine:

bash
# Pull the latest code
git fetch origin
git checkout main

# Run the same commands that failed in CI
# For test failures:
npm test
# or
pytest
# or
go test ./...

# For build failures:
npm run build

# For lint failures:
npm run lint

If the failure only happens in CI, check for environment differences:
- Different Node/Python/Go version
- Missing environment variables
- Cached dependencies vs fresh install
- Different OS or architecture

Use Docker to match CI environment more closely:

bash
# Run the same Docker image used in pipeline
docker run -it --rm -v $(pwd):/app -w /app node:18 bash

# Inside the container, run your commands
npm ci
npm test

Bitbucket provides a way to debug locally using Docker - you can run an identical container to find the root cause interactively.

4Fix test failures

If the pipeline failed due to failing tests, address the test or code issues:

Common test failure scenarios:

1. Assertion failure - Update the test or fix the code:

javascript
// Fix the actual code
function calculateTotal(items) {
  return items.reduce((sum, item) => sum + item.price, 0); // was missing initial value
}

2. Snapshot mismatch - Update snapshots if changes are intentional:

bash
npm test -- --updateSnapshot
# or
jest --updateSnapshot

3. Async test timeout - Increase timeout or fix async handling:

javascript
test('async operation', async () => {
  jest.setTimeout(10000); // Increase timeout
  const result = await slowOperation();
  expect(result).toBeDefined();
}, 10000);

4. Environment-dependent test - Mock external dependencies:

javascript
// Mock API calls that may fail in CI
jest.mock('./api', () => ({
  fetchData: jest.fn().mockResolvedValue({ data: 'test' })
}));

After fixing, push your changes:

bash
git add .
git commit -m "fix: resolve failing tests"
git push origin main
5Fix build and compilation errors

For build failures, address the compilation or bundling issues:

TypeScript/JavaScript build errors:

bash
# Check for TypeScript errors locally
npx tsc --noEmit

# Common fixes:
# - Add missing type definitions
# - Fix type mismatches
# - Install missing @types packages
npm install --save-dev @types/node

Import/export issues:

typescript
// Wrong - named vs default export mismatch
import MyComponent from './MyComponent'; // expects default export
export const MyComponent = () => {}; // but this is named export

// Fix:
export default MyComponent;
// or
import { MyComponent } from './MyComponent';

Missing dependencies:

bash
# Make sure all dependencies are listed in package.json
npm install missing-package --save

# Use npm ci in pipelines for reproducible builds
# bitbucket-pipelines.yml:
script:
  - npm ci  # Not 'npm install'
  - npm run build

Docker build issues:

yaml
# Ensure you're using the right image
image: node:18

# Or specify a custom Docker image
definitions:
  services:
    docker:
      memory: 2048  # Increase memory if needed
6Handle environment variable issues

Fix problems related to missing or incorrect environment variables:

Set repository variables in Bitbucket:
1. Go to Repository settings > Pipelines > Repository variables
2. Add your variables (e.g., API_KEY, DATABASE_URL)
3. Mark sensitive values as "Secured"

Reference variables in bitbucket-pipelines.yml:

yaml
image: node:18

pipelines:
  default:
    - step:
        script:
          - echo "Deploying to $ENVIRONMENT"
          - npm run deploy

Define variables inline for non-sensitive values:

yaml
definitions:
  variables:
    NODE_ENV: &node_env "production"

pipelines:
  default:
    - step:
        script:
          - export NODE_ENV=*node_env
          - npm run build

Debug missing variables:

yaml
script:
  # Print available environment variables (be careful not to expose secrets!)
  - printenv | grep -v PASSWORD | grep -v SECRET | grep -v KEY
  - npm run build

Common variable issues:
- Variable name typo (case-sensitive)
- Variable set in wrong scope (repository vs deployment)
- Secured variables not available in pull request builds from forks

7Resolve memory limit errors (exit code 137)

If your pipeline fails with exit code 137, it's running out of memory:

text
error: command failed with exit code 137

Exit code 137 means the process was killed by the system (SIGKILL), typically due to memory exhaustion.

Solution 1: Use a larger build step size:

yaml
pipelines:
  default:
    - step:
        size: 2x  # Doubles memory from 4GB to 8GB
        script:
          - npm ci
          - npm run build

Available sizes:
- 1x: 4 GB RAM (default)
- 2x: 8 GB RAM (uses 2x build minutes)

Solution 2: Optimize memory usage:

yaml
script:
  # For Jest - limit parallel workers
  - npm test -- --maxWorkers=2
  # or run sequentially
  - npm test -- --runInBand

  # For Node.js - increase heap size
  - export NODE_OPTIONS="--max-old-space-size=4096"
  - npm run build

Solution 3: Split into multiple steps:

yaml
pipelines:
  default:
    - step:
        name: Build
        script:
          - npm ci
          - npm run build
        artifacts:
          - dist/**
    - step:
        name: Test
        script:
          - npm ci
          - npm test
8Fix timeout errors

If your pipeline exceeds time limits, optimize or extend the timeout:

Increase step timeout:

yaml
pipelines:
  default:
    - step:
        name: Long Running Tests
        max-time: 60  # Maximum time in minutes (default is 120)
        script:
          - npm run test:e2e

Optimize to reduce build time:

1. Use caching effectively:

yaml
definitions:
  caches:
    npm: ~/.npm
    node: node_modules

pipelines:
  default:
    - step:
        caches:
          - npm
          - node
        script:
          - npm ci
          - npm test

2. Run tests in parallel:

yaml
pipelines:
  default:
    - parallel:
        - step:
            name: Unit Tests
            script:
              - npm run test:unit
        - step:
            name: Integration Tests
            script:
              - npm run test:integration

3. Skip unnecessary steps:

yaml
pipelines:
  pull-requests:
    '**':
      - step:
          name: Quick Tests Only
          script:
            - npm ci
            - npm run test:unit  # Skip slow e2e tests for PRs
9Handle piped command exit codes

By default, piped commands in bash only report the exit code of the last command, potentially hiding errors:

Problem:

yaml
script:
  # This won't fail even if npm test fails!
  - npm test | tee test-output.log

Solution 1: Enable pipefail:

yaml
script:
  - set -o pipefail
  - npm test | tee test-output.log

Solution 2: Chain commands properly:

yaml
script:
  # Run test and save output, failing if tests fail
  - npm test 2>&1 | tee test-output.log; test ${PIPESTATUS[0]} -eq 0

Capturing exit codes correctly:

yaml
script:
  # Wrong - printf intercepts $?
  - failing-command
  - echo "Exit code: $?"  # Always shows 0!

  # Correct - combine on same line
  - set +e
  - failing-command; exit_code=$?; set -e
  - echo "Exit code: $exit_code"
  - if [ $exit_code -ne 0 ]; then exit $exit_code; fi

Allow specific commands to fail:

yaml
script:
  # This command can fail without failing the pipeline
  - npm run optional-check || true
  # This one will still fail the pipeline
  - npm test
10Retry the pipeline for transient failures

For temporary failures (network issues, flaky tests), you can retry:

Manual retry:
1. Navigate to the failed pipeline
2. Click the Rerun button to retry failed steps
3. Or click Run pipeline to start fresh

Rerun only failed steps:
Bitbucket Pipelines allows you to rerun only the failed steps rather than the entire pipeline, saving time and build minutes.

Configure automatic retries in script:

yaml
script:
  # Retry a flaky command up to 3 times
  - |
    for i in 1 2 3; do
      npm run flaky-test && break || {
        if [ $i -lt 3 ]; then
          echo "Attempt $i failed, retrying..."
          sleep 10
        else
          echo "All attempts failed"
          exit 1
        fi
      }
    done

Trigger pipeline via API:

bash
curl -X POST \
  -u "$BITBUCKET_USERNAME:$BITBUCKET_APP_PASSWORD" \
  "https://api.bitbucket.org/2.0/repositories/{workspace}/{repo}/pipelines/" \
  -H "Content-Type: application/json" \
  -d '{
    "target": {
      "ref_type": "branch",
      "type": "pipeline_ref_target",
      "ref_name": "main"
    }
  }'

Push an empty commit to trigger:

bash
git commit --allow-empty -m "ci: retry pipeline"
git push origin main

Advanced notes

### Understanding Exit Codes in Bitbucket Pipelines

Common exit codes and their meanings:

| Exit Code | Meaning | Common Cause |
|-----------|---------|--------------|
| 1 | General error | Test failure, script error |
| 2 | Misuse of command | Invalid arguments |
| 126 | Permission problem | Script not executable |
| 127 | Command not found | Missing binary/tool |
| 128 | Invalid exit argument | Script returned invalid code |
| 137 | SIGKILL (128+9) | Out of memory, killed by system |
| 139 | SIGSEGV (128+11) | Segmentation fault |
| 143 | SIGTERM (128+15) | Job timeout, terminated |

### Pipeline Artifacts for Debugging

Preserve logs and test results from failed pipelines:

yaml
pipelines:
  default:
    - step:
        script:
          - npm test -- --coverage
        artifacts:
          - coverage/**
          - test-results/**
          - logs/**

Artifacts are available for download from the pipeline UI even when the step fails.

### Branch-Specific Pipeline Behavior

The bitbucket-pipelines.yml file must exist in the branch being built:

yaml
pipelines:
  # Runs for any branch without a specific pipeline
  default:
    - step:
        script:
          - npm test

  # Runs only for specific branches
  branches:
    main:
      - step:
          script:
            - npm run deploy:prod

    develop:
      - step:
          script:
            - npm run deploy:staging

    'feature/*':
      - step:
          script:
            - npm test -- --coverage

### Push Limits

Bitbucket accepts up to five branches in one push. Exceeding this limit may prevent pipelines from triggering. Push branches individually if you hit this limit.

### Using Services for Integration Tests

For tests requiring databases or other services:

yaml
definitions:
  services:
    postgres:
      image: postgres:15
      variables:
        POSTGRES_DB: test_db
        POSTGRES_USER: test
        POSTGRES_PASSWORD: test

pipelines:
  default:
    - step:
        services:
          - postgres
        script:
          - export DATABASE_URL="postgresql://test:test@localhost:5432/test_db"
          - npm run db:migrate
          - npm test

### Docker-in-Docker (DinD)

For pipelines that build Docker images:

yaml
definitions:
  services:
    docker:
      memory: 2048

pipelines:
  default:
    - step:
        services:
          - docker
        script:
          - docker build -t myapp .
          - docker push myapp

### Debugging with SSH

For complex failures, you can SSH into a pipeline build (requires configuration):

yaml
pipelines:
  custom:
    debug:
      - step:
          script:
            - echo "Debug session ready"
          # Enable SSH access in Bitbucket settings first

### Conditional Steps

Skip steps based on conditions:

yaml
pipelines:
  default:
    - step:
        name: Deploy
        script:
          - npm run deploy
        condition:
          changesets:
            includePaths:
              - "src/**"
              - "package.json"

Frequently asked questions

What does "Pipeline failed for branch main" mean?
When you see "Pipeline failed for branch main" (or any other branch name), Bitbucket is telling you that your CI/CD pipeline did not complete successfully. A pipeline fails when any step returns a non-zero exit code, indicating an error. yml file as bash/shell commands.
How do I fix "Pipeline failed for branch main"?
This Bitbucket Pipelines error occurs when one or more steps in your CI/CD pipeline fail during execution. The failure can stem from test failures, build errors, configuration issues, or resource limits. To resolve it, examine the pipeline logs, identify the root cause, and fix the underlying issue in your code or configuration.
What causes "Pipeline failed for branch main"?
Test suite failures - unit tests, integration tests, or end-to-end tests not passing Build or compilation errors - code doesn't build successfully Linting or code style violations found by ESLint, Prettier, or similar tools
Is the "Pipeline failed for branch main" error serious?
It is a medium-severity error — more of a blocker than a risk. The steps above resolve it.

Official resources & further reading