Creating Empty Test Folder in Jenkins Workspace

Abstract: Create empty test folders in Jenkins workspaces using shell commands or pipeline steps to prevent script failures from missing directories.

Created: 2026-09-11 by
Creating an empty test folder in the Jenkins workspace is straightforward using either a simple shell command or a dedicated plugin. The most reliable method involves adding a build step to execute mkdir -p for your desired directory path, ensuring it exists before any test scripts run. This guarantees a clean slate for your automation framework without manual intervention.

Understanding the Workspace Context

Every Jenkins job operates within a specific workspace directory on the agent machine where the build takes place. This location is dynamic and changes with each job configuration. When you need to structure your project, such as separating source code from test artifacts, creating directories programmatically is essential. Unlike local development environments where you might manually create folders, CI/CD pipelines require explicit instructions to establish this structure at runtime. The workspace is typically located at ${WORKSPACE} relative to the current build context. If you are running tests that expect a specific folder structure, such as test-results or output, failing to create these directories can cause script failures. For instance, Python or Java test runners often throw exceptions if they attempt to write logs to a non-existent path. Therefore, establishing this hierarchy early in the build process prevents downstream errors.

Method 1: Using Shell Scripts

The most common approach for Linux-based agents is to use a shell execution step. This method provides immediate control over the file system and requires no additional plugins. You can add a "Execute shell" build step at the beginning of your pipeline or freestyle project. Inside the script, use the mkdir command with the -p flag. This flag ensures that parent directories are created if they do not exist and suppresses errors if the directory already exists. For example, to create a folder named tests inside your workspace, you would enter the following command:
mkdir -p ${WORKSPACE}/tests
This command is robust because it handles nested paths automatically. If you need deeper structures like tests/unit and tests/integration, the same command works seamlessly. After execution, you can verify the creation by listing the contents of the workspace using ls -la. This visual confirmation helps debug issues during initial setup. If you are using Windows agents, the syntax differs slightly. You should use the PowerShell or Command Prompt build steps instead. In PowerShell, the equivalent command is New-Item -ItemType Directory -Force -Path "${env:WORKSPACE}\tests". The -Force parameter mimics the behavior of -p in Unix systems, ensuring idempotent execution. Always ensure your agent has the necessary permissions to write to the workspace directory.

Method 2: Using Pipeline Syntax

For teams utilizing Jenkins Pipelines (Jenkinsfile), the logic is embedded directly into the Groovy script. This approach offers better version control and reusability across multiple jobs. You can define a stage specifically for environment setup before your actual test execution stage. This keeps your pipeline organized and makes the intent clear to other developers reviewing the code. In a declarative pipeline, you might structure your code like this:
pipeline {
    agent any
    stages {
        stage('Setup') {
            steps {
                sh 'mkdir -p ${WORKSPACE}/test-output'
            }
        }
        stage('Run Tests') {
            steps {
                // Your test execution commands here
                sh './run_tests.sh'
            }
        }
    }
}
By isolating the folder creation in its own stage, you can easily add conditional logic later. For example, you might only create the folder if a certain parameter is passed. This modularity is a key advantage of pipeline-as-code over freestyle projects. It also allows you to integrate with other tools more easily, as seen when passing environmental variable URL strings to Gradle tasks, where setup steps must precede task execution.

Best Practices for Automation

Consistency is critical in automated testing. Relying on manual folder creation leads to drift between environments. Always automate the setup phase. Additionally, consider cleaning up old data. While creating new folders is important, removing stale results from previous runs prevents clutter. You can combine creation and cleanup in a single step using rm -rf followed by mkdir -p. However, be cautious with removal commands to avoid deleting unintended files. Another best practice is to document the expected folder structure in your README or pipeline comments. This helps new team members understand why specific directories exist. It also aids in troubleshooting when tests fail to generate reports. If your test runner expects output in ./reports but you created ./test-reports, the build will fail silently or produce empty artifacts. Clear naming conventions reduce cognitive load and maintenance overhead. For more advanced automation scenarios, such as integrating with version control systems, ensure your workspace is properly initialized. Understanding how to connect Git to Jenkins server ensures that your code checkout happens before your folder creation steps, preventing race conditions. If your workflow involves complex batch operations, refer to guides on batch files and commands to optimize your shell scripts for performance.

Frequently Asked Questions

What happens if the folder already exists?

Using the -p flag with mkdir prevents errors if the directory is present. The command becomes idempotent, meaning it does nothing if the target state is already achieved. This safety feature is crucial for continuous integration builds that run repeatedly.

Can I create folders in parallel stages?

Yes, Jenkins allows parallel execution of stages. However, be careful if multiple stages try to create the same directory simultaneously. While usually safe, it is better to centralize setup steps to avoid potential permission conflicts or race conditions.

How do I verify the folder was created?

You can add a subsequent shell step that lists the directory contents using ls or dir (on Windows). Checking the console output after the build completes confirms whether the path exists and contains the expected items.

Does this work with Docker agents?

Yes, as long as the container image includes the mkdir utility. Most standard Linux images include core utilities. Ensure your Dockerfile installs any necessary tools before executing the Jenkins agent.

Should I commit these folders to Git?

No. The Jenkins workspace is ephemeral and typically excluded from version control via .gitignore. Creating folders in the workspace is a runtime activity, not a source code change. Committing generated directories clutters the repository and causes merge conflicts.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More