Home > Mobile >  How to run a bash script on wsl with powershell?
How to run a bash script on wsl with powershell?

Time:05-08

On my current directory on Windows, I have the following script file simple_script.sh:

#!/bin/bash
echo "hi from simple script"

I wish to run this script on wsl via the powershell command line.

Using the wsl command, I could not find a way to tell wsl to invoke the script code.

The following command works (I think)

wsl bash -c "echo hi from simple script"

However when trying to load the script content into a variable and running it does not work as expected:

$simple_script = Get-Content ./simple_script.sh
wsl bash -c $simple_script

Fails with:

bash: -c: option requires an argument

I tried a few variants. using Get-Content with the -Raw flag seems to make the first word in the string to print (but not the whole string). commands that don't contain '"' characters seems to work sometimes. But I haven't found a consistent way.

A similar looking question doesn't seem to work directly with the wsl, and doesn't seem to run a script file that resides on the Windows file system.

CodePudding user response:

To run the script on wsl you simply invoke bash

> bash simple_script.sh
hi from simple script

To save it in a variable and have it run as a bash script within wsl or powershell, there is no need for Get-Content

> $simple_script = bash /mnt/c/Users/user-name/path/to/simple_script.sh
> Write-Output $simple_script
hi from simple script

NOTE: Powershell has an alias mapping echo to Write-Output, so you could also use echo

> $simple_script = bash /mnt/c/Users/user-name/path/to/simple_script.sh
> echo $simple_script
hi from simple script

You can also grab the content if that was your initial aim.

> Get-Content simple_script.sh
#!/bin/bash
echo "hi from simple script"
 
> $content = Get-Content .\simple_script.sh
> Write-Output $content
#!/bin/bash
echo "hi from simple script"

  • Related