Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to Run Commands in WSL2-Ubuntu from a Script?

Learn how to create a Windows script that opens WSL2-Ubuntu and runs commands automatically.
PowerShell terminal running WSL2-Ubuntu commands on a Windows PC, illustrating automation and scripting for seamless development workflows. PowerShell terminal running WSL2-Ubuntu commands on a Windows PC, illustrating automation and scripting for seamless development workflows.
  • 🚀 WSL2 runs a real Linux kernel on Windows, enabling efficient command execution without a virtual machine.
  • 🔄 Automating WSL2 commands with scripts improves workflow efficiency for developers and system administrators.
  • ⚙️ Batch and PowerShell scripts provide different automation approaches for executing Linux commands in WSL2.
  • 📅 Windows Task Scheduler can be used to automate recurring Linux scripts in WSL2.
  • 🛠️ Debugging techniques like log redirection and PowerShell try-catch help diagnose script failures in WSL2.

How to Run Commands in WSL2-Ubuntu from a Script?

Automating tasks in development environments saves time and increases efficiency. With Windows Subsystem for Linux 2 (WSL2), developers can harness the power of Linux commands directly within Windows. However, manually entering these commands repeatedly can become tedious. This guide explores how to use batch scripts and PowerShell to automate Linux command execution in WSL2-Ubuntu, streamlining workflows and improving productivity.

Understanding WSL2 and Its Automation Benefits

WSL2 allows Windows users to run a full Linux distribution natively, eliminating the need for a separate virtual machine. Unlike WSL1, which translated system calls, WSL2 incorporates an actual Linux kernel, leading to improved performance and full system call compatibility (Microsoft, 2022).

Key Benefits of Automation in WSL2:

  1. Faster Environment Setup – Automatically configure development environments.
  2. Streamlined Software Deployment – Execute repeatable commands for software installation and maintenance.
  3. Task Scheduling and Execution – Run automated tasks at startup or on a schedule.
  4. Cross-Platform Development – Use Linux tools within Windows without dual-booting or separate VMs.

Running Commands in WSL2-Ubuntu

WSL2 provides the wsl command to run Linux commands directly from Windows CLI tools like Command Prompt or PowerShell.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Basic Examples:

Run a single command in WSL2:

wsl ls -l

Execute a script inside WSL2:

wsl /home/user/myscript.sh

Combining multiple commands in one execution:

wsl bash -c "cd /home && mkdir newfolder && ls -l"

Creating a Basic Batch Script for WSL2 Execution

Batch scripting provides a simple way to automate WSL2 commands.

Sample Batch Script (script.bat):

@echo off
wsl echo "Hello from WSL2"
wsl uname -r

How It Works:

  1. The script runs WSL2 and prints a message.
  2. The uname -r command displays the WSL2 kernel version.
  3. Save the script with a .bat extension and double-click to execute it.

Automating WSL2-Ubuntu with PowerShell Scripts

PowerShell provides advanced automation capabilities and error handling.

Basic PowerShell Script (script.ps1):

wsl uname -a

Capturing Command Output in PowerShell:

$output = wsl ls -l
Write-Output $output

Advantages of PowerShell Over Batch:

✅ Better error handling with try-catch
✅ Easier script maintenance
✅ Ability to store and manipulate outputs

Running Multiple Commands in WSL2 Using Scripts

Batch Script Example:

@echo off
wsl bash -c "cd /home && mkdir testdir && ls -l"

PowerShell Script Example:

wsl bash -c "cd /home; mkdir testdir; ls -l"

Redirecting Output to a Log File:

wsl ls -l > wsl_output.txt

This will create a text file (wsl_output.txt) with the command output.

Passing Parameters to WSL2 Scripts

Scripts in WSL2 can accept parameters dynamically.

PowerShell Script with a Parameter:

param (
    [string]$folderName
)

wsl bash -c "mkdir $folderName"

Running the script like this:

.\script.ps1 TestFolder

Will create a new folder named "TestFolder" inside WSL2.

Using Arguments in Batch Scripts:

@echo off
set FOLDERNAME=%1
wsl bash -c "mkdir %FOLDERNAME%"

Executing script.bat MyFolder will create "MyFolder" inside WSL2.

Scheduling WSL2 Scripts with Windows Task Scheduler

Automating WSL2 scripts with Task Scheduler ensures they run at startup or on a recurring basis.

Steps to Schedule a PowerShell Script in Task Scheduler:

  1. Open Task Scheduler from the Windows Start menu.
  2. Click Create Task and name it (e.g., "WSL2 Automation").
  3. Under the Trigger tab, set the schedule (e.g., startup or daily execution).
  4. Under the Action tab, choose Start a program and enter:
    powershell.exe -ExecutionPolicy Bypass -File "C:\path\to\your\script.ps1"
    
  5. Click OK, enable the task, and test execution.

Handling Errors and Debugging WSL2 Scripts

Common issues causing WSL2 script failures include:
❌ Incorrect file paths
❌ Execution policy restrictions for PowerShell
❌ Missing dependencies in WSL2

Debugging Techniques:

  1. Capture errors from command execution:
    wsl ls -l 2> error.log
    
  2. Use try-catch in PowerShell for better script resilience:
    try {
       wsl uname -a
    } catch {
       Write-Output "Error encountered: $_"
    }
    

Advanced Tricks for WSL2 Automation

Using Environment Variables:

$env:WSL_DISTRO = "Ubuntu-22.04"
wsl bash -c "echo Running on $WSL_DISTRO"

Automating Docker in WSL2:

wsl docker run -d -p 8080:80 nginx

WSL2 in CI/CD Pipelines:

WSL2 can be integrated into automated workflows in GitHub Actions or Azure DevOps for CI/CD (Red Hat, 2023).

Real-World Use Cases and Best Practices

Common Tasks Automated in WSL2:

Development Environment Setup:

wsl sudo apt update && sudo apt install -y nodejs npm

Automating Tests:

wsl pytest tests/

Reducing Manual Deployment Errors:

wsl bash -c "git pull && npm install && npm start"

Best Practices:

  • Use PowerShell for complex automation.
  • Implement proper logging for debugging.
  • Use scheduled tasks for consistent automation.
  • Automate CI/CD processes using WSL2 scripts.

Next Steps

Using scripting techniques to run commands in WSL2-Ubuntu can streamline development tasks and improve efficiency. Try automating common workflows, explore advanced integrations, and schedule automated tasks to optimize your system.


Citations

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading