Use a bash script if it exists on the path, otherwise use an executable

2

I want to use a bash script if it exists on the path, and otherwise, I would like to use an executable.

alias build='xctool.sh'
type -a xctool.sh || alias build='xcodebuild'
build -scheme "${APP_SCHEME}" archive

So in this example I want to use xctool.sh instead of xcodebuild if it's available. Otherwise I want xcodebuild to be used.

The error I get is "build: command not found"

Where am I going wrong?

Tycho Pandelaar

Posted 2014-01-24T13:36:41.830

Reputation: 137

Answers

2

What you describe works perfectly if run on the command line, if you're having problems, I assume you are trying to do this as part of a script (hint: this is the kind of thing you want to mention in your question).

Scripts are run in a non-interactive shell and in this kind of shell aliases are not expanded. From man bash:

   Aliases are not expanded when the shell is not interactive, unless  the
   expand_aliases  shell option is set using `shopt`

So, you have a few choices. First, you can activate aliases in your script:

#!/usr/bin/env bash

shopt -s expand_aliases
alias build='xctool.sh'
type -a xctool.sh 2>/dev/null || alias build='xcodebuild'
build -scheme "${APP_SCHEME}" archive

Alternatively, you can avoid aliases altogether by using eval:

#!/usr/bin/env bash

build='xctool.sh'
type -a xctool.sh 2>/dev/null || build='xcodebuild'
$build -scheme ${APP_SCHEME} archive

terdon

Posted 2014-01-24T13:36:41.830

Reputation: 45 216

Thanks! I'll try your last suggestion first thing monday morning. Sounds like a winner. – Tycho Pandelaar – 2014-01-24T19:02:04.497

Wouldn't the last line work equally well without eval? (and be less prone to expansion problems): $build -scheme "${APP_SCHEME}" archive – Adrian Pronk – 2014-01-28T10:51:34.277

@AdrianPronk good point, answer edited, thanks. – terdon – 2014-01-28T19:28:06.750

1

I don't know, what type should do here; but when I get you right, something like this may be helpful:

[ -x ./xctool.sh ] && alias build='./xctool.sh' || alias build='xcodebuild'

leu

Posted 2014-01-24T13:36:41.830

Reputation: 111

1

Have a look at man test -e / -f flags.

Maybe some thing like this works:

[ -f xctool.sh ] && xctool.sh || xcodebuild

konqui

Posted 2014-01-24T13:36:41.830

Reputation: 504