Mark Needham

Thoughts on Software Development

A dirty hack to get around aliases not working in a shell script

with 4 comments

In another script I’ve been working on lately I wanted to call ‘mysql’ but unfortunately on my machine it’s ‘mysql5′ rather than ‘mysql’.

I have an alias defined in ‘~/.bash_profile’ so I can call ‘mysql’ from the terminal whenever I want to.

alias mysql=mysql5

Unfortunately shell scripts don’t seem to have access to this alias and the only suggestion I’ve come across while googling this is to source ‘~/.bash_profile’ inside the script.

Since others are going to use the script and might have ‘~/.bashrc’ instead of ‘~/.bash_profile’ I didn’t really want to go down that route.

At this stage a colleague of mine came up with the idea of creating a soft link from mysql to mysql5 inside a folder which is already added to the path.

We located mysql5…

> which mysql5
/opt/local/bin/mysql5

…and then created a soft link like so:

cd /opt/local/bin/mysql5
ln -s mysql5 mysql

And it works!

Of course t’is pure hackery so I’d be interested if anyone knows a better way of getting around this.

Written by Mark Needham

November 24th, 2010 at 6:48 pm

Posted in Shell Scripting

Tagged with

  • Phil

    It’s not all that hackish to provide a link to the expected program if you can justify a global default – it’s pretty commonplace (see /etc/alternatives on Ubuntu and presumably therefore Debian).

    If you really want to avoid the link you might consider setting a variable on your system in /etc/profile or similar (e.g. export MYSQL_COMMAND=mysql5) and invoking ${MYSQL_COMMAND:-mysql} which uses the default in systems where no environment variable is set.

    Or you might just check for the special-case program in the script e.g.:

    mysql=/usr/bin/mysql
    if [ ! -x $mysql ]
    then
    mysql=/usr/local/bin/mysql5
    fi

    $mysql whatever

  • http://greggigon.com Greg Gigon

    Hi Mark
    Actually it is a way most of the linux distribution are dealing with different versions of same software. Check out the /usr/bin folder. There is a plenty of symbolic links there :)

  • http://pseudofish.com/blog Geoff Wilson

    Symlinks work great for global re-naming of commands.

    If you want to change default behaviour, then create a shell script with the same name and put that in the right location or symlink to it. This works if you need to set custom environment variables or perform some other kind of setup that you have in your ~/.bash_profile.

    Greg’s right too, have a look in /usr/bin. On a Mac, try:

    file /usr/bin/* | grep -v Mach

  • Colin McD

    Stumbling upon the same problem. I have found the answer here http://ubuntuforums.org/showthread.php?t=1255937

    Basically alias will only work with interactive shells. Because we are running inside the script alias fails. Solution as per article above.