Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

How do I make the following function work correctly

# Install git on demand
function git()
{
    if ! type git &> /dev/null; then sudo $APT install git; fi
    git $*;
}

by making git $* call /usr/bin/git instead of the function git()?

share|improve this question

2 Answers 2

up vote 2 down vote accepted

Like this:

# Install git on demand
function git()
{
    if ! type -f git &> /dev/null; then sudo $APT install git; fi
    command git "$@";
}

The command built-in suppresses function lookup. I've also changed your $* to "$@" because that'll properly handle arguments that aren't one word (e.g., file names with spaces).

Further, I added the -f argument to type, because otherwise it'll notice the function.

You may want to consider what to do in case of error (e.g., when apt-get install fails).

share|improve this answer
    
Thorough answer! –  Nordlöw Apr 3 '14 at 22:15

Or perhaps a more generic function being able to run any command. In this case the '-f' can be replaced with '-t'. The collision with the function will not occur.

function runcmd()
{
  if ! type -t $1 >/dev/null; then
    pkg=$(apt-file search -x "bin.*$1\$" | cut -d: -f1)
    sudo apt-get install $pkg
  fi
  eval "$@"
}

Of course 'apt-get install' errors must be handled.

share|improve this answer
    
Good one. La Suède Deux Points ;) Thanks mate. –  Nordlöw Apr 4 '14 at 16:19

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.