Skip to content

Instantly share code, notes, and snippets.

@JeremySkinner
Created August 7, 2018 13:11
Show Gist options
  • Save JeremySkinner/2a54334c2cbb24df56bcc5f021199bb1 to your computer and use it in GitHub Desktop.
Save JeremySkinner/2a54334c2cbb24df56bcc5f021199bb1 to your computer and use it in GitHub Desktop.
Handle path translation for calling windows executables from WSL
#!/usr/bin/php
<?php
// In php first element of $argv is the path to the current script.
$a = $argv;
if(count($a) === 2) {
// Single argument. Just launch it.
shell_exec($a[1]);
}
elseif(count($a) > 2) {
$cmd = $a[1];
array_splice($a, 0, 2);
for($i = 0; $i < count($a); $i++) {
$value = $a[$i];
if (strpos($value, '/') > -1) {
// Do path transalation
// If it doesn't start with a /, convert to full path
if ($value[0] != '/') {
$real = realpath($value);
if ($real) {
$value = $real;
}
}
// We now have the full path. Run wsl on it.
$path = shell_exec("wslpath -w $value");
if ($path) {
// Escape slashes
$value = str_replace('\\', '\\\\', $path);
}
}
$a[$i] = $value;
}
$args = implode(' ', $a);
shell_exec("$cmd $args");
}
@JeremySkinner
Copy link
Author

Converts WSL paths to Windows paths which makes it easier to launch windows executables from wsl. For example, for VS Code I could add a code function into my bashrc:

function code {
  launch.php code $@
}

...and now I can type code ~/code/somefile rather than code $(wslpath -w ~/code/somefile)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment