Adam Haile
Adam Haile

Reputation: 31329

best way to run different commands depending on OS in bash

In a bash script is there an "official" way to run different commands based on, for example, OS version. I mean in a way that you can basically set it once at the top and then call it the same way everywhere else. I've tried to use aliases but that seems to be a crapshoot and doesn't really work on some systems (one is Windows 7 using win-bash).

For example, this is what I tried:

if [ "$(uname)" = "Darwin" ]; then
    alias p4cli=./bin/p4
else
    alias p4cli=C:\bin\p4.exe
fi

p4cli login

It works on Mac if I use shopt -s expand_aliases but win-bash doesn't have shopt. I'm assuming there's a better way than aliases to do this?

Upvotes: 5

Views: 2805

Answers (4)

anubhava
anubhava

Reputation: 784988

To determine underlying OS in bash it is better to depend on env variable OSTYPE. The bash manpage says that the variable OSTYPE stores the name of the operation system:

OSTYPE Automatically set to a string that describes the operating system on which bash is executing. The default is system- dependent.

if [[ "$OSTYPE" == "darwin"* ]]; then
   p4cli="./bin/p4"
else
   p4cli="C:\bin\p4.exe"
fi

"$p4cli" login

Upvotes: 4

chepner
chepner

Reputation: 530960

Make the process that calls p4cli responsible for adding the correct directory to its PATH variable. Then you need only call p4cli login without worry about its exact location.

Presumably, you would do this from a machine-specific (or at least OS-specific) .bash_profile, which can just hard-code the correct directory.

Upvotes: 1

sampson-chen
sampson-chen

Reputation: 47269

How about saving the command in a variable?

if [ "$(uname)" = "Darwin" ]; then
    p4cli='./bin/p4'
else
    p4cli='C:\bin\p4.exe'
fi

$p4cli login

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798526

Use variables, not aliases.

if [ "$(uname)" = "Darwin" ]; then
    p4cli=(./bin/p4)
else
    p4cli=('C:\bin\p4.exe')
fi

"${p4cli[@]}" login

We make the variables arrays so that arguments can be added to the commands later if required.

Upvotes: 2

Related Questions