Create Bash Scripts On Windows With Windows Subsystem For Linux Wsl

Gombloh
-
create bash scripts on windows with windows subsystem for linux wsl

Install and manage WSL 2, distros, and kernel for a real Linux environment on Windows. - Work with VS Code/Visual Studio, Docker, databases, and GPUs within WSL. - Combines Windows-Linux commands and optimizes storage for maximum performance. - Master Bash scripting: variables, loops, cron, and debugging with set -x and set -e. If you work on Windows but need the power of LinuxWSL lets you have the best of both worlds: a complete Linux distribution integrated with your system, without heavy virtual machines or dual-booting.

Here, you'll learn how to set up WSL, understand its key commands, and, most importantly, how to create and run Bash scripts without complicating your life. This text brings together everything important in one guide: step-by-step installation (quick and manual method), distribution management, file storage, use with Windows Terminal, VS Code, and Visual Studio, containers and databases, GPU acceleration, Windows-Linux interoperability, and a practical Bash scripting block (variables, input/output, conditionals, loops, cron, and debugging). By the end, you'll have a ready-made environment and the foundation to automate any task.

What is WSL and why use Bash on Windows? WSL (Windows Subsystem for Linux) It allows you to install Linux distributions as Windows applications, with the kernel and user tools ready to run commands, compile code, and automate processes. This offers true interoperability: running Windows binaries from Linux and vice versa, sharing file systems, and combining commands in both directions. Its main objective is make life easier for administrators and developers Those who need Linux tooling on Windows without setting up complex infrastructures.

It's also great for beginners who want to try Linux without risking their installation: if something breaks in the distro, you can reinstall it and that's it, without touching Windows. In addition, with WSL you avoid one of the typical pains of the Linux desktop: hardware supportCompatibility is guaranteed here, and if that weren't enough, you can access ext4 drives from Windows via WSL, something that's unthinkable natively without external tools. Versions, requirements, and key differences (WSL 1 vs.

WSL 2) WSL 2 is the recommended version: it uses a lightweight virtual machine with a real Linux kernel managed by Hyper‑V, improving system call compatibility and performance (faster I/O, up to several hundred percent under certain loads). Windows 11 already includes WSL 2 by default, and in Windows 10 it is enabled if you meet version 1903 (build 18362) or later on x64, and 2004 (19041) on ARM64.

To check if your computer is x64 or ARM64 and review the build, you can use Win+R -> winver and, in PowerShell, check the system type with: systeminfo | find "Tipo de sistema" . If your build doesn't arrive At the very least, update Windows before making the jump to WSL 2.

Even with its advantages, there are limits: the network and certain peripherals They may perform worse due to virtualization layers; WSL 1 doesn't support kernel-level functionality (classic Docker doesn't work there), and some distros in the Store don't come with systemd by default, which makes it difficult to launch traditional services like on a pure server. Installing WSL: Simplified Method and Manual Method If you are on a recent build, the shortcut is a single command.

Open PowerShell or CMD as administrator and run: wsl --install This command enables the components WSL and Virtual Machine Platform, download and install the latest kernel, set WSL 2 as default, and install Ubuntu (reboot likely). You can list available distros with wsl --list --online y choose another with: wsl --install <Distribution Name> .

If your system does not allow the simplified method, do the manual installation from PowerShell with administrator privileges: - Enable WSL 1: dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart - Activate Virtual Machine Platform: dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart - Reboot and then install the WSL 2 (x64) kernel package: https://wslstorestorage.blob.core.windows.net/wslblob/wsl_update_x64.msi - On ARM64, use: https://wslstorestorage.blob.core.windows.net/wslblob/wsl_update_arm64.msi - Defines WSL 2 by default: wsl --set-default-version 2 - Install a Linux distribution from the Microsoft Store (Ubuntu, Debian, openSUSE, Fedora, etc.).

The first time you open the distro from the Start menu, create a username and password Linux. Then, update the packages with: sudo apt update && sudo apt upgrade . Distro management and essential WSL commands WSL commands are run from PowerShell/CMD with wsl (in Bash you can also use wsl.exe). To consult everything: wsl --help These are the most useful ones for everyday use: - Install WSL or a specific distro: wsl --install owsl --install <Distribution Name> (options:--distribution ,--no-launch ,--web-download ).

List available distros: wsl --list --online (equivalent towsl -l -o ). - List installed distros: wsl --list --verbose (owsl -l -v ), with WSL status and version (1/2). Flags:--all ,--running ,--quiet . - Set version by distro: wsl --set-version <Distribution Name> <1|2> . - Set WSL 1/2 as default: wsl --set-default-version <1|2> . - Choose default distro: wsl --set-default <Distribution Name> . - Start at home: wsl ~ (and on Linux:cd ~ ). - Run a specific distro/user: wsl --distribution <Distribution Name> --user <User Name> .

Update WSL: wsl --update (option--web-download ). - State/versioning: wsl --status ywsl --version . - Run as user: wsl --user <Username> . Change the default user of a distro:<DistributionName> config --default-user <Username> . - Shutdown/terminate: wsl --shutdown ywsl --terminate <Distribution Name> . - IP addresses: wsl hostname -I (WSL 2 VM IP). Windows IP as seen from WSL 2:ip route show | grep -i default | awk '{ print $3}' .

Export/import: wsl --export <Distribution Name> <FileName> (tar or--vhd ),wsl --import <Name> <InstallLocation> <FileName> (--vhd ,--version ),wsl --import-in-place <Name> <FileName.vhdx> . - Uninstall (unregister): wsl --unregister <DistributionName> (delete data from that distro permanently). - Mount/unmount disks: wsl --mount <DiskPath> (--vhd ,--name ,--bare ,--type ,--partition ,--options ), Andwsl --unmount <DiskPath> . - Old commands: wslconfig.exe ,bash ,lxrun are obsolete.

File storage and performance The golden rule is save the projects where you are going to workIf you'll be using Linux tools in the distro's terminal, place the files on the WSL file system (ext4). If you'll be working from PowerShell or Windows apps, keep them on NTFS. You can open the current WSL directory in Explorer with explorer.exe . (includes the period). Typical paths for projects in WSL are \\wsl$\<DistroName>\home\<UserName>\Proyecto ; avoid routes such as C:\Users\<UserName>\Project o /mnt/c/Users/<UserName>/Project when compiling from Linux to avoid performance penalties.

Terminal and editors: Windows Terminal, VS Code, and Visual Studio Windows Terminal It offers tabs, panels, Unicode/UTF-8 support, and GPU acceleration for text rendering. Each installed distro creates a profile that you can customize to your liking (including themes, colors, and shortcuts). For editing and debugging, the most convenient way is Visual Studio Code with Remote – WSL. Install it on Windows, open the distro and run code . to launch the remote server.

You'll be able to use the entire VS Code extension ecosystem as if you were on native Linux. If you work in C++, Visual Studio 2022 Integrates WSL to build and debug CMake projects on Windows, WSL, and SSH from the same instance, choosing the target system with one click. Containers, databases, and GPU acceleration With WSL 2 you can use DockerDesktop and Development Containers to isolate dependencies and maintain reproducible environments. It's ideal for team workflows and keeping the system clean.

Setting up databases within WSL it is directMySQL, PostgreSQL, MongoDB, Redis, Microsoft SQL Server, or SQLite work normally. Install them using your distro's package manager or Docker containers if you prefer. For intensive loads (e.g., ML training), set up GPU acceleration in WSL and take advantage of your graphics card from your Linux environment on Windows. Interoperability: Windows-Linux mixed commands From PowerShell, run Linux tools by prepending wsl.

For example, listing a directory with ls -la Linux native since C:\temp: wsl ls -la You can also combine pipes from both worlds: wsl ls -la | findstr "git" or, the other way around, dir | wsl grep git . And from WSL, launch Windows binaries as notepad.exe .bashrc . A useful example of mixin: in Bash, Filters the output of Windows ipconfig with GNU tools: ipconfig.exe | grep IPv4 | cut -d: -f2 .

From PowerShell it would be: ipconfig.exe | wsl grep IPv4 | wsl cut -d: -f2 . Mounting disks and graphics applications With wsl –mount You can connect physical disks or VHD/VHDX (ext4 by default) and use them within your distros. Unmounting is as simple as wsl --unmount <DiskPath> ; without a route, everything is dismantled. La running Linux GUI applications In WSL, it's supported in recent builds (WSLg), and in older environments, there were alternatives like Kali's Win‑KeX (desktop experience via VNC).

You'll need modern builds (e.g., >= 21362) for the full experience with audio. Bash Scripting in WSL: Fundamentals That Matter A Bash script is a text file with commands that the shell executes in order. It allows you to automate maintenance, manage files, process data, deploy applications, and build custom utilities.

The typical structure includes the shebang on the first line and then the commands: #!/bin/bash echo "Hola, mundo" To create and run your first script: open an editor (nano, vim, code), save script.sh with your content, executable mark to chmod +x script.sh and run it with ./script.sh o bash script.sh . Variables, valid names, and I/O in Bash There are no strict types in Bash: variables store text, numbers, etc. Assign with pais=España and reads with $pais Avoid using spaces when assigning and names that begin with digits.

Conventions: begins with a letter or underscore, use letters, numbers, and underscores, be case-sensitive, and avoid reserved words (if, then, etc.). Valid names: my_var, Account2; invalid: 2var, my var, my-var. To capture input of the user: read nombre . From file: while read linea; do echo "$linea"; done < input.txt . With arguments: $1 , $2 ... For output: print with echo , redirects to file with > (overwrites) or >> (adds), and pipes output between commands with pipes to build flows more complex.

Basic commands, conditionals and loops Master the essentials: cd, ls, mkdir, touch, rm, cp, mv, cat, grep, chmod, sudo, df, history, ps. With man consult the man pages for each tool. Decisions are modeled with if/elif/else (logical operators -a AND, -o OR) to check numeric, string, or file conditions (for example, -f , -d , -e ). the loops while y for repeat actions: in while you control the condition, in for Iterates lists or ranges. Increments counters with (( i+=1 )) when it touches.

With CASE You compare an expression with patterns and execute blocks based on the match; you end each block with ;; and use * as the default case. Scheduling with cron and automation Cron schedule recurring tasks: open the editor with crontab -e and defines times with five fields (minute, hour, day of month, month, day of week). A typical example at midnight would be 0 0 * * * /ruta/script.sh . To check if a cron was executed in Ubuntu/Debian, check / var / log / syslog.

Depending on the distro, the location of logs may vary, so adjust your search accordingly. Debugging and robustness in scripts Activate trace mode with set -x or execute bash -x script.sh to see each command expanded. If you want to abort at the first error, use set -e at the beginning of the script. The last exit code lives in $?: zero means success, another value indicates failure. Intercalates echo strategically to inspect variables and flows when something doesn't add up.

Typical errors when running scripts and how to solve them If you see Permission denied, you are missing the execution bit: chmod +x script.sh . If it appears command not found, check the shebang, the syntax and that the file is not actually a .txt. Ante syntax errors (unexpected token), check quotes, parentheses and paired do/done or then/fi. For problems with PATH, add your folder (e.g., ~/bin) with export PATH=$PATH:~/bin en ~/.bashrc and recharge with source ~/.bashrc .

WSL: Troubleshooting Common Issues If you see the kernel message when moving to WSL 2, install the update from MSI packages linked before. If a distro won't boot and gives 0x8007019e, the WSL feature in Windows Features is probably not enabled. The mistakes 0x80070003 or 0x80370102 During installation they usually indicate virtualization disabled in BIOS/UEFI: enable it and repeat. 0 x 80070003 It can also appear if you try to install on a drive other than the system drive (WSL only runs on the drive with Windows, usually C:).

If you see WslRegisterDistribution with 0x8007019e, enable the feature from Control Panel -> Programs and Features -> Turn Windows features on or off, checking "Windows Subsystem for Linux" and reboot. When the system says there are no distros installed, throw them at least once from the Start menu before invoking them from the command line; this completes their initial setup.

Differences with VM, dual boot and Docker In front of one full virtual machine (VirtualBox/VMware), WSL 2 boots in seconds, consumes less RAM and integrates with Windows, but a VM gives you more control and a traditional desktop UI if you need it for very heavy loads. En dual bootYou can get the most out of Linux, but you have to reboot to switch OSes. With WSL, you gain speed and interoperability (NTFS from Linux and ext4 accessible from Windows via WSL), without reserving partitions or duplicating environments.

Docker It's not a complete OS, but rather isolated containers for specific services. It's ideal for reproducible deployments; it integrates very well with WSL 2, but be careful with the idea of "developing in production": maintain good practices and layers. Notes on privacy on platforms When browsing content on communities like Reddit, it's common to find cookie notices and privacy policies ("We value your privacy"), which do not affect the use of WSL but should be kept in mind when browsing resources.

With all the above you already have the complete map To work with WSL and master Bash scripting from Windows: install or migrate to WSL 2, organize your storage based on where you run tools, rely on Windows Terminal and VS Code, use Docker and databases when appropriate, combine Windows and Linux commands, and automate with cron. If something goes wrong, WSL management commands and debugging guidelines will get you out of trouble.

People Also Asked

Bash Scripting on Windows with WSL: A Complete Guide?

With all the above you already have the complete map To work with WSL and master Bash scripting from Windows: install or migrate to WSL 2, organize your storage based on where you run tools, rely on Windows Terminal and VS Code, use Docker and databases when appropriate, combine Windows and Linux commands, and automate with cron. If something goes wrong, WSL management commands and debugging guide...

How to Script Bash on Windows with WSL: A Practical Guide?

Here, you'll learn how to set up WSL, understand its key commands, and, most importantly, how to create and run Bash scripts without complicating your life. This text brings together everything important in one guide: step-by-step installation (quick and manual method), distribution management, file storage, use with Windows Terminal, VS Code, and Visual Studio, containers and databases, GPU accel...

Create Bash scripts on Windows with Windows Subsystem for ...?

Here, you'll learn how to set up WSL, understand its key commands, and, most importantly, how to create and run Bash scripts without complicating your life. This text brings together everything important in one guide: step-by-step installation (quick and manual method), distribution management, file storage, use with Windows Terminal, VS Code, and Visual Studio, containers and databases, GPU accel...

Set up a WSL development environment | Microsoft Learn?

Setting up databases within WSL it is directMySQL, PostgreSQL, MongoDB, Redis, Microsoft SQL Server, or SQLite work normally. Install them using your distro's package manager or Docker containers if you prefer. For intensive loads (e.g., ML training), set up GPU acceleration in WSL and take advantage of your graphics card from your Linux environment on Windows. Interoperability: Windows-Linux mixe...

How to Script Bash on Windows Using WSL - en.movilforum.com?

Here, you'll learn how to set up WSL, understand its key commands, and, most importantly, how to create and run Bash scripts without complicating your life. This text brings together everything important in one guide: step-by-step installation (quick and manual method), distribution management, file storage, use with Windows Terminal, VS Code, and Visual Studio, containers and databases, GPU accel...