【问题标题】:WSL - How to fallback to exe when linux binary is not available in BashWSL - 当 Linux 二进制文件在 Bash 中不可用时如何回退到 exe
【发布时间】:2021-11-22 15:28:01
【问题描述】:

我需要做的是编写既可在常规 Unix 系统上运行的脚本,又可在 WSL 上运行的脚本,并在 PATH 中未安装 linux 时尝试使用 EXE 版本的命令。

这是我正在使用的当前代码,但我想知道是否可以使用更简单、不那么冗长的方法?

if ! command -v docker && command -v docker.exe &>/dev/null; then
  DOCKER=docker.exe
else
  DOCKER=docker
fi

if ! command -v cargo &>/dev/null && command -v cargo.exe &>/dev/null; then
  CARGO=cargo.exe
else
  CARGO=cargo
fi

【问题讨论】:

    标签: bash windows-subsystem-for-linux


    【解决方案1】:

    像往常一样遇到此类问题,创建一个函数。

    docker() {
        if hash docker >/dev/null 2>&1; then
           command docker "$@"
        elif hash docker.exe >/dev/null 2>&1; then
           docker.exe "$@"
        else
           # just to get nice docker: command not found message
           command docker "$@"
        fi
    }
    # will run docker.exe or docker
    docker run -ti --rm alpine echo hello world
    

    我如何为任何给定的命令概括这一点?

    哈,这很有趣。请注意,eval 是邪恶的。

    gen_functions() {
       for i; do
           eval "
    $i() {
        if hash $i >/dev/null 2>&1; then
           command $i \"\$@\"
        elif hash $i.exe >/dev/null 2>&1; then
           $i.exe \"\$@\"
        else
           command $i \"\$@\"
        fi
    }
    "
        done
    }
    
    # will define function for each argument
    gen_functions docker cargo diesel
    

    或者,更有选择性,等等:

    mask_function() {
        local cmd
        cmd=$1
        shift
        if hash "$cmd" >/dev/null 2>&1; then
           command "$cmd" "$@"
        elif hash "$cmd".exe >/dev/null 2>&1; then
           "$cmd".exe "$@"
        else
           command "$cmd" "$@"
        fi
    }
    docker() { mask_function docker "$@"; }
    cargo() { mask_function cargo "$@"; }
    # etc.
    

    【讨论】:

    • 我如何为任何给定的命令概括这一点?即码头、货物、柴油等。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多