1

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()?

2

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).

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

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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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