jacob_pro
jacob_pro

Reputation: 111

WSL - How to fallback to exe when linux binary is not available in Bash

What I need to be able to do is write scripts which work on both a regular Unix system, but also work on WSL and try to use the EXE versions of commands when the linux one isn't installed / in PATH.

This is the current code I am using, but I am wondering if there is a simpler less verbose method I can use?

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

Upvotes: 1

Views: 304

Answers (1)

KamilCuk
KamilCuk

Reputation: 141623

As usuall with such problems, create a function.

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

how can i generalise this for any given command?

Hah, that's fun. Note that eval is evil.

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

or alternatively, more selectively, etc.:

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.

Upvotes: 3

Related Questions