I'm trying to create a simple script that will dump all my aliases into a file that bash can load when it starts up, while making sure the alias of - to popd works properly:

alias -p | sed 's/alias -=/alias -- -=/' > ~/.bash_aliases

If I run that on the command line, it seems to work, but if I put it in a script and run that (with #!/bin/bash at the top and chmod +x), instead I get an empty file. Can someone tell me what bit of bash lore I'm missing?

If it matters, I'm using bash v4.2.10.

2 Answers 2


A shell script inherits the calling program's environment variables and such, but it does not inherit things like aliases and command history.

If all of your aliases are in a common location, like ~/.bashrc, you could source that file into your script first:

. $HOME/.bashrc

Then you would have, in that shell script's execution context, all of the aliases defined in the .bashrc file.

If your aliases are defined all over the place, there is no easy way to consolidate them. You would have to write this "save all my aliases" as a function instead. You could put something like this in your ~/.bash_profile, for example:

function dumpalias {
    alias -p | sed 's/alias -=/alias -- -=/' > ~/.bash_aliases

Then, after logging out and back in, you can say dumpalias to get the behavior you want.

  • Thanks. I didn't realise aliases were not inherited. It works perfectly as a function.
    – Wolf
    Jun 1, 2011 at 20:58
  • you don't need to log out and in, just source or . your .bash_profile Jun 1, 2011 at 23:59
  • Of course you don't. I recommended that only because .bash_profile often contains things like PATH extensions that are best done once per session only. Jun 2, 2011 at 7:52

When you put it in a script and execute it, you're starting a new shell, which doesn't inherit the aliases from your current shell. So, the script is saving the shell's aliases; there just aren't any aliases defined in the shell where those commands are executed.

You can source the script to execute it in the current shell:

. /path/to/script

Or, you could write it as a shell function.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .