How To Run Commands In Wsl2 Ubuntu From A Script
Creating and running Bash scripts on Windows is easier than ever with WSL., the layer that allows you to use a complete Linux environment integrated into Microsoft's operating system without setting up heavy virtual machines or configuring dual boots. If your goal is to automate tasks, work with the terminal, and take advantage of classic Linux tools, this walkthrough will take you from installation to script development and debugging.
In the next sections You will see how to enable WSL and choose a distro (e.g., Ubuntu), master basic commands, write your first Bash scripts with best practices, and deploy them to production with cron. You'll also learn how to integrate Linux and Windows interoperably (cross-platform commands, file access, VS Code/Visual Studio, Docker, databases, GPUs, GUI), along with a troubleshooting guide and the differences between WSL, virtual machines, dual boot, and containers. What is WSL and why use it for Bash scripts?
WSL (Windows Subsystem for Linux) is a Windows feature that runs a Linux environment within Windows., with direct file system integration and the ability to launch Bash commands, tools, and scripts as if you were using a native distro. With WSL 2, which uses a real Linux kernel in a lightweight VM, performance and compatibility are significantly improved over WSL 1.
Its advantages include compatibility with CLI tools (grep, sed, awk, etc.), cross-file system access, and Docker support on WSL 2.If you work in mixed environments and need to automate processes, build, test, or deploy, WSL reduces friction and eliminates the need to switch between operating systems or maintain heavy VMs.
Preparing the Environment in Windows Enable WSL and the Virtual Machine Platform from an administrator-privileged consoleYou can do this with PowerShell or CMD very directly using the simplified command: wsl --install If you prefer to do it step by step, enable the features and leave WSL 2 as default: dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart wsl --set-default-version 2 In some cases WSL 2 requires manually updating the Linux kernel.; download the official Microsoft package when prompted. After installation or feature changes, restart the computer.
Install a Linux distribution from the Microsoft Store (e.g. Ubuntu). When you open it for the first time, it creates your user and password Linux (the input will be blind: you won't see any characters when you type).
Verify that you're using WSL 2: wsl --list --verbose Installing and setting up Ubuntu on WSL Once Ubuntu is installed, update the packages to have the latest versions and patches.: sudo apt update && sudo apt upgrade -y Check or change the distro's WSL version (if installed on WSL 1): wsl --list --verbose wsl --set-version Ubuntu 2 Install common development utilities according to your needs: sudo apt install git curl build-essential -y Access Windows files from Ubuntu using mount points: units appear in /mnt For example, drive C: cd /mnt/c To improve performance: If you are going to work with Linux tools, store the project in the WSL file system to minimize latencies, for example in \\wsl$<DistroName>\home\<UserName>\Proyecto , and avoid intensive loads in locations such as /mnt/c/Users/<User>/Proyecto .
Getting Started in the Terminal: Useful Basic Commands Navigate through the file system and list contents: cd /home ,cd ~ ,pwd ls ,ls -a Manage files and directories: mkdir mi_carpeta ,touch archivo.txt ,cp origen.txt destino.txt mv archivo.txt renombrado.txt ,rm archivo.txt ,rm -r carpeta Edit with terminal editors: nano archivo.txt it's simple; vim archivo.txt It is powerful (to go out, use :q and Enter).
Install and update packages: sudo apt install htop sudo apt update sudo apt upgrade -y Permits and ownership: grants execution to a script with chmod +x script.sh and changes owner with sudo chown usuario:grupo archivo.txt .
Your first Bash script: structure and execution Bash scripts end in .sh (optional) and start with a shebang to indicate the interpreter: #!/bin/bash Create a simple script, make it executable and run it: echo "#!/bin/bash" > hola.sh echo "echo \"Hola, mundo\"" >> hola.sh chmod +x hola.sh ./hola.sh You can also run it explicitly with sh or bash: sh hola.sh o bash hola.sh .
Example with interaction: requests a route, lists its contents, and displays the current date: #!/bin/bash echo "Hoy es" `date` echo -e "\nIngresa la ruta al directorio" read the_path echo -e "\nTu ruta contiene:" ls "$the_path" Comments, variables, and conventions in Bash Use comments with # to document and disable lines: # Esto es un comentario Variables do not have native types in Bash; store numbers, text, or characters.
Assign and use with = and expose with $ : pais=España echo "$pais" Good naming practices: starts with a letter or underscore, uses letters, numbers and _ , case-sensitive, avoids spaces, hyphens, and reserved words. Valid: nombre_cuenta , miVar ; invalid: 2var , mi var , mi-var . Input and output in your scripts Read user input to read : read nombre echo "Hola, $nombre" Read from file with while loop: while read linea; do echo "$linea"; done < input.txt Command line arguments: $1 , $2 , ...
echo "Hola, $1!" # ./script.sh Zaira -> Hola, Zaira! Generates output to echo , redirects and attachments: echo "Hola, Mundo!" echo "Texto" > output.txt (overwrites)echo "Más texto" >> output.txt (attached)ls > files.txt (redirects output from a command) Basic shell commands you'll use every day Some must-haves for scripts and administration: cd , ls , mkdir , touch , rm , cp , mv , echo , cat , grep , chmod , sudo , df , history , ps , and man to consult manuals.
Conditionals, loops and case in Bash Evaluate conditions with if/elif/else (and logical -a, or -o): read n if [ "$n" -gt 0 ]; then echo "Positivo"; elif [ "$n" -lt 0 ]; then echo "Negativo"; else echo "Cero"; fi while loop: repeats while the condition is true; includes a counter: i=0; while [ $i -lt 10 ]; do echo $i; (( i+=1 )); done for loop: for a fixed number of iterations or elements: for i in {1..5}; do echo $i; done Case: pattern vs.
options, with wildcards and default case: fruta="manzana" case "$fruta" in manzana) echo "Fruta roja";; banana) echo "Fruta amarilla";; *) echo "Fruta desconocida";; esac Schedule scripts with cron Cron allows you to run automatic tasks at defined times..
Example syntax: * * * * * sh /ruta/a/script.sh useful examples: 0 0 * * * /ruta/a/script.sh (every midnight)*/5 * * * * /ruta/a/script.sh (every 5 minutes)0 6 * * 1-5 /ruta/a/script.sh (Monday to Friday, at 6:00)0 0 1-7 * * /ruta/a/script.sh (first 7 days of the month)0 12 1 * * /ruta/a/script.sh (1st of the month at noon) Manage your tasks with crontab -e y crontab -l . On Ubuntu/Debian, /var/log/syslog records cron logs for debugging.
Debugging and Troubleshooting Bash Scripts Turn on debug mode to see each command: #!/bin/bash set -x # depuración Check exit codes to $? to detect errors: comando_critico if [ $?
ne 0 ]; then echo "Hubo un error."; fi Use echos for inspection: prints values and streams from the script: echo "Valor de x: $x" Force quit on error to set -e To stop the script if any command fails: #!/bin/bash set -e Windows ⇄ Linux interoperability and key WSL commands Run Linux tools from PowerShell or CMD to wsl : wsl ls -la Combine commands from both systems: wsl ls -la | findstr "git" o dir | wsl grep git Launch Windows tools from Bash adding .exe : notepad.exe .bashrc Mixed execution of network calls: ipconfig.exe | grep IPv4 | cut -d: -f2 Quick summary of useful WSL commands: wsl --install ,wsl --list --online ,wsl --list --verbose wsl --set-version <Distro> <1|2> wsl --set-default-version 2 wsl --shutdown - IPs: wsl hostname -I (IP in WSL 2) andip route show | grep -i default | awk '{ print $3 }' for Windows IP from WSL Storage, Windows Terminal, and Performance Open the current WSL directory in Windows Explorer with: explorer.exe .
For better performance, work on Linux projects in the WSL file system and avoid intensive accesses in /mnt from Linux tools. From Windows, it keeps files in NTFS. Windows Terminal It is ideal for managing multiple sessions (tabs, panels, Unicode support, GPU acceleration and themes), and customizing profiles for each installed distro. Editor and development tools: VS Code and Visual Studio Visual Studio Code works perfectly with WSL Using the Remote Development extension. Open your projects with: code .
Visual Studio 2022 Includes native support for WSL in C++ projects with CMake, making it easy to compile and debug in different environments — Windows, WSL, and SSH servers — from a single instance. Git, credentials, and best practices Use Git in WSL to manage versions and configure the credential manager if you're working with remote repositories.
Pay attention to line endings (LF/CRLF) and use the built-in commands in VS Code to make operations easier: git clone https://github.com/usuario/repositorio.git Docker, databases, GPUs, and graphics applications With WSL 2, Docker Desktop for Windows works seamlessly, allowing the use of development containers without the need for additional virtual machines. For local development, install and run databases such as MySQL, PostgreSQL, MongoDB, Redis, SQL Server or SQLite, allowing you to reproduce production Linux environments and making work easier.
Configure GPU acceleration for intensive loads and machine learning, leveraging graphics hardware for better performance. Linux applications with a graphical interface are possible in WSL (Windows 11 with WSLg makes this easier). On systems without direct support, there are alternatives with integrated solutions such as Win‑KeX. Mount external or USB drives in WSL 2 You can connect and mount physical disks and VHD/VHDX in WSL 2 using: wsl --mount <DiskPath> useful options: --vhd for virtual disks, --type <Filesystem> (default ext4), --partition <Nº> y --options with FS parameters.
To disassemble, use: wsl --unmount <DiskPath> Differences: WSL 1 vs WSL 2, VM, dual boot and Docker WSL 1 translates system calls, while WSL 2 runs a real Linux kernel in a lightweight VM.This improves compatibility and performance, and also natively supports tools like Docker. Compared to a traditional virtual machineWSL 2 boots almost instantly, consumes fewer resources, and integrates much better with Windows. However, a VM provides greater isolation and control, useful in complex networks or entire environments. Regarding dual bootWSL avoids reboots and offers superior interoperability.
If you need to take advantage of all the Linux hardware and graphical interface, dual-booting is still a more straightforward option. Compared to DockerRemember that a container is an isolated, minimal service, while WSL offers a general-purpose development environment. They're complementary: use containers for specific services and WSL for the entire development environment. Limitations and considerations Some WSL limitations (especially in WSL 1) affect compatibility and performance.In WSL 2, the network goes through layers of virtualization, which can impact very sensitive scenarios.
Certain peripherals or low-level services may not function the same as on native Linux. Also, check if your distro uses systemd if you need to run services like on a conventional server. Interoperability is very good: : access to ext4 via WSL, mixed commands, and the ability to reinstall the distro without affecting Windows if something goes wrong. Security and user management in the distro The user created on first run will be the default and will have sudo permissions.
You can change the password with passwd or, if you forget it, reset it from PowerShell by logging in as root: wsl -u root passwd <usuario> To set a default user on one distro, use: ubuntu config --default-user <usuario> Troubleshooting common problems The installer may ask you to update the WSL 2 kernel.Download and install the official package and reboot. For errors like 0x80070003 or 0x80370102, enable virtualization in the BIOS and make sure the WSL and VM components are enabled.
For error 0x8007019e (WslRegisterDistribution), enable WSL from Windows Features or using DISM. "WSL has no distribution installed": Open the distro at least once from the Start menu before using it on the console. Distributions in wrong location (0x80070003): Preferably, install the distros on the same drive as the Windows system, usually C:. poor performance: verify that you are using WSL 2 (wsl -l -v ) and try to store your projects in the WSL file system, avoiding paths in /mnt for intensive loads.
Software compatibility issues: If you need specific kernel features, consider a VM or native Linux. You can now write, program, debug, and automate Bash scripts on Windows., integrating tools like Git, VS Code, Docker, and databases, with the option to use cron for scheduled tasks and experiment with GUIs whenever possible; all with fine-grained storage control, key commands, and common error resolution to make your work easier.
People Also Asked
- How to Run Commands in WSL2-Ubuntu from a Script?
- How to run a bash script on wsl with powershell? - Stack Overflow
- Basic commands for WSL | Microsoft Learn
- How to run command when starting a machine in WSL2
- How to Script Bash on Windows with WSL: A Practical Guide
- Using a batch file on Windows to automate Ubuntu in WSL
- Install Ubuntu on WSL 2 - Ubuntu on WSL documentation
How to Run Commands in WSL2-Ubuntu from a Script?
ne 0 ]; then echo "Hubo un error."; fi Use echos for inspection: prints values and streams from the script: echo "Valor de x: $x" Force quit on error to set -e To stop the script if any command fails: #!/bin/bash set -e Windows ⇄ Linux interoperability and key WSL commands Run Linux tools from PowerShell or CMD to wsl : wsl ls -la Combine commands from both systems: wsl ls -la | findstr "git" o di...
How to run a bash script on wsl with powershell? - Stack Overflow?
ne 0 ]; then echo "Hubo un error."; fi Use echos for inspection: prints values and streams from the script: echo "Valor de x: $x" Force quit on error to set -e To stop the script if any command fails: #!/bin/bash set -e Windows ⇄ Linux interoperability and key WSL commands Run Linux tools from PowerShell or CMD to wsl : wsl ls -la Combine commands from both systems: wsl ls -la | findstr "git" o di...
Basic commands for WSL | Microsoft Learn?
In the next sections You will see how to enable WSL and choose a distro (e.g., Ubuntu), master basic commands, write your first Bash scripts with best practices, and deploy them to production with cron. You'll also learn how to integrate Linux and Windows interoperably (cross-platform commands, file access, VS Code/Visual Studio, Docker, databases, GPUs, GUI), along with a troubleshooting guide an...
How to run command when starting a machine in WSL2?
To disassemble, use: wsl --unmount <DiskPath> Differences: WSL 1 vs WSL 2, VM, dual boot and Docker WSL 1 translates system calls, while WSL 2 runs a real Linux kernel in a lightweight VM.This improves compatibility and performance, and also natively supports tools like Docker. Compared to a traditional virtual machineWSL 2 boots almost instantly, consumes fewer resources, and integrates much bett...
How to Script Bash on Windows with WSL: A Practical Guide?
In the next sections You will see how to enable WSL and choose a distro (e.g., Ubuntu), master basic commands, write your first Bash scripts with best practices, and deploy them to production with cron. You'll also learn how to integrate Linux and Windows interoperably (cross-platform commands, file access, VS Code/Visual Studio, Docker, databases, GPUs, GUI), along with a troubleshooting guide an...