Bash on Windows - alias for exe files

前端 未结 3 1949
说谎
说谎 2021-01-13 00:30

I am using the Bash on Ubuntu on Windows, the way to run bash on Windows 10. I have the Creators update installed and the Ubuntu version is 16.04.

I was playing rece

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-13 01:28

    I've faced the same problem when trying to use Docker for Windows from WSL.

    Had plenty of existing shell scripts that run fine under Linux and mostly under WSL too until failing due to docker: command not found. Changing everywhere docker to docker.exe would be too cumbersome and non-portable.


    Tried workaround with aliases in ~/.bashrc as here at first:

    shopt -s expand_aliases
    alias docker=docker.exe
    alias docker-compose=docker-compose.exe
    

    But it requires every script to be run in interactive mode and still doesn't work within backticks without script modification.


    Then tried exported bash functions in ~/.bashrc:

    docker() { docker.exe "$@"; }
    export -f docker
    docker-compose() { docker-compose.exe "$@"; }
    export -f docker-compose
    

    This works. But it's still too tedious to add every needed exe.


    Finally ended up with easier symlinks approach and a modified wslshim custom helper script.

    Just add once to ~/.local/bin/wslshim:

    #!/bin/bash -x
    cd ~/.local/bin && ln -s "`which $1.exe`" "$1" || ln -s "`which $1.ps1`" "$1" || ln -s "`which $1.cmd`" "$1" || ln -s "`which $1.bat`" "$1"
    

    Make it executable: chmod +x ~/.local/bin/wslshim

    Then adding any "alias" becomes as easy as typing two words:

    $ wslshim docker
    + cd ~/.local/bin
    ++ which docker.exe
    + ln -s '/mnt/c/Program Files/Docker/Docker/resources/bin/docker.exe' docker
    
    $ wslshim winrm
    + cd ~/.local/bin
    ++ which winrm.exe
    + ln -s '' winrm
    ln: failed to create symbolic link 'winrm' -> '': No such file or directory
    ++ which winrm.ps1
    + ln -s '' winrm
    ln: failed to create symbolic link 'winrm' -> '': No such file or directory
    ++ which winrm.cmd
    + ln -s /mnt/c/Windows/System32/winrm.cmd winrm
    

    The script auto picks up an absolute path to any windows executable in $PATH and symlinks it without extension into ~/.local/bin which also resides in $PATH on WSL.

    This approach can be easily extended further to auto link any exe in a given directory if needed. But linking the whole $PATH would be an overkill. )

提交回复
热议问题