Home > Blockchain >  WSL $PATH is empty when passing commands in one-line
WSL $PATH is empty when passing commands in one-line

Time:01-30

On Windows 11, when using WSL 2 (Ubuntu20.04LTS) in-line, using wsl -- command, my PATH variable is empty and programs installed are not found. I'm writing a Powershell script, and I'd like to run linux commands in one line of script, but this PATH issue is preventing me from doing so.

When running WSL using --, I get this:

λ wsl --user vanyle -- echo $PATH

λ wsl --user vanyle -- python
zsh:1: command not found: python
λ wsl -- python
zsh:1: command not found: python

But if I first log into WSL, everything works fine.

λ wsl
WSL-ZSH /mnt/c/Users/vanyle/
λ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/usr/lib/wsl/lib
WSL-ZSH /mnt/c/Users/vanyle/
λ python
Python 3.8.10 (default, Mar 25 2022, 14:53:42)
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

CodePudding user response:

Both PowerShell and POSIX-compatible shells such as bash and zsh use symbol $ to refer to variables.

Since you want the WSL-side shell to interpret variable $PATH you must prevent PowerShell from expanding it up front; which you can do my selectively `-escaping $ characters or - more simply - by enclosing $PATH in a verbatim (single-quoted) string ('...'):

wsl --user vanyle -- echo '$PATH'

Note: If you want to pass multiple commands and/or need shell features such as >, it's simpler to use the -e option and call your shell executable (e.g. bash or zsh) explicitly, passing it a command line as a single string via the -c option; e.g.:

wsl --user vanyle -e bash -c 'echo $PATH; date'

Note: Calling a POSIX-compatible shell with the -c option for non-interactive execution of a command does not cause profile or initialization files such as ~/.bash_profile, ~/.bashrc, or ~/.zshrc - by default this happens only when entering an interactive shell session (passing neither a -c argument nor a shell-script path).

To get the same shell environment as in an interactive session, also pass the -i and -l options; e.g.:

wsl --user vanyle -e zsh -ilc 'echo $PATH; date'
  • Related