Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoking bash aliases in Fabric scripts

I have aliases in a ~/.bash_aliases file on a remote ubuntu server. The file is loaded in the standard way from a ~/.bashrc file, like so:

if [ -f ~/.bash_aliases ]; then
    . ~/.bash_aliases
fi

That ~/.bashrc file in turn is loaded (also in a standard way) from a ~/.profile file which looks like this:

if [ "$BASH" ]; then
  if [ -f ~/.bashrc ]; then
    source ~/.bashrc
    echo ".profile loaded .bashrc"
  fi
fi
mesg n

I've found that my aliases were unavailable in my fabric commands, e.g. when I do this in a fabric script:

run("aliased_command")

I get this output:

run: aliased_command
out: .profile loaded .bashrc
out: /bin/bash: aliased_command: command not found
Fatal error: run() encountered an error (return code 127) while executing 'aliased_command'

Now I managed to reproduce this outside of fabric by logging into the server with ssh, and running :

~# /bin/bash -l -c aliased_command 

from the shell (n.b. /bin/bash -l -c is fabric's default, see here) I get the same output:

.profile loaded .bashrc:
/bin/bash: aliased_command: command not found

After a fair bit of searching on related topics, I read somewhere that aliases aren't exported for non-interactive shells, and I then managed to fix this using /bin/bash -l -c -i (-i sets bash to interactive mode).

I then added the following to my fabfile.py:

env.shell = "/bin/bash -l -c -i" 

Now I can use aliases in my fabric commands... just great!


So my questions are:

  • Are there any problems with this solution? If so, what should I be doing?

  • Does anyone else have a problem running aliases in their fabfiles?

  • Is there any obvious reason why I might have this issue and others wouldn't?

  • Can anyone point me to links etc. that describe this problem and a resolution? And also explain how they found them... : )

like image 912
JobJob Avatar asked Jun 30 '12 07:06

JobJob


People also ask

Do bash aliases work in scripts?

Making alias work in bash scriptVariables can be used in the bash script to set the preferred options for any command and those variables can be referred in the later section of script to suffice the need of alias inside scripts.

How do you display aliases?

To view the alias for a particular name, enter the command alias followed by the name of the alias. Most Linux distributions define at least some aliases. Enter an alias command to see which aliases are in effect. You can delete the aliases you do not want from the appropriate startup file.


1 Answers

Here is the quick answer to the main issue, to save someone reading my long question, just add

env.shell = "/bin/bash -l -i -c" 

to your fabfile.py and you should be able use aliases in your fabric commands just great!

like image 73
JobJob Avatar answered Nov 01 '22 18:11

JobJob