Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a bash function to wrap another command?

I am trying to write a function wrapper for the mysql command

If .my.cnf exists in the pwd, I would like to automatically attach --defaults-file=.my.cnf to the command

Here's what I'm trying

function mysql {
  if [ -e ".my.cnf" ]; then
    /usr/local/bin/mysql --defaults-file=.my.cnf "$@"
  else
    /usr/local/bin/mysql "$@"
  fi
}

The idea is, I want to be able to use the mysql command exactly as I was before, only, if the .my.cnf file is present, attach it as an argument

Question: Will I run into any trouble with this method? Is there a better way to do it?

If I specify --defaults-file=foo.cnf manually, that should be used instead of .my.cnf.

like image 675
Mulan Avatar asked Oct 24 '25 18:10

Mulan


1 Answers

Your function as written is perfectly fine. This is a touch DRYer:

function mysql {
    if [ -e ".my.cnf" ]; then
        set -- --defaults-file=.my.cnf "$@"
    fi
    /usr/local/bin/mysql "$@"
}

That set command puts your my.cnf argument at the beginning of the command line arguments

Only if the option is not already present:

function mysql {
    if [[ -e ".my.cnf" && "$*" != *"--defaults-file"* ]]; then
        set -- --defaults-file=.my.cnf "$@"
    fi
    /usr/local/bin/mysql "$@"
}
like image 128
glenn jackman Avatar answered Oct 26 '25 09:10

glenn jackman