Tuesday, July 1, 2025

Add ‘Open Bash Here’ into Visual Studio

 With the rise of cross-platform development, the need for Linux tools like bash has become more prevalent, even in Windows environments. Developers often need to run bash scripts for tasks such as deploying services to Azure or managing containers. An integrated bash prompt in Visual Studio, opening directly at a file’s location, can significantly streamline this process. Here we create a script amd config.VS to run it


Why

In a mixed development environment where Windows and Linux tools are both essential, there’s a challenge: Windows uses a different file path structure compared to Linux. When developing on Windows with Visual Studio but needing to run Linux-based tools (like bash scripts), there’s a disconnect — the paths don’t translate automatically between systems. This is where a Linux script comes into play.


Creating the script

To bridge this gap, we created a Linux script that performs path translation. It takes a Windows file path as input, converts it into a Linux-friendly path, and then opens a bash shell at that location.


vi ~/.open-wsl-bash.sh


#!/bin/bash

win_path=$1

# Replace single backslashes with double backslashes

win_path=${win_path//\\//\\\\}

# Translate the Windows path to WSL path

wsl_path=$(wslpath -u "$win_path")

# Navigate to the directory and open bash

cd "$wsl_path" && exec bash

Script Breakdown

#!/bin/bash: Shebang line to indicate the script uses bash.

win_path=$1: Assigns the first argument passed to the script to win_path.

win_path=${win_path//\\//\\\\}: Doubles the backslashes to escape them properly for bash.

wsl_path=$(wslpath -u "$win_path"): Uses wslpath to convert the Windows path to a WSL path.

cd "$wsl_path" && exec bash: Changes to the directory and opens a new bash shell.

This script is an essential piece of the puzzle for a seamless development experience across Windows and WSL environments.


Adding the External Command in Visual Studio

Find the path to wt.exe.

Navigate to Tools > External Tools.

Click “Add” and configure:

Title: Open Bash Here

Command: Path to your wt.exe.

Arguments: --profile "Ubuntu-20.04" -- bash -c "bash ~/.open-wsl-bash.sh '$(ItemDir)'"

Initial directory: $(ItemDir)

Visual Studio: Adding external command

“Ubuntu-20.04” is the name of my Linux Windows Terminal profile. Change it to your Linux profile name.



Conclusion

With this setup, you’ll have a seamless “Open Bash Here” command in Visual Studio that improves the development workflow by providing quick access to a Linux bash environment at the location of your current file.




No comments:

Post a Comment