Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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.

share|improve this question

2 Answers 2

up vote 3 down vote accepted

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.

share|improve this answer
    
Thanks. I didn't realise aliases were not inherited. It works perfectly as a function. –  Wolf Jun 1 '11 at 20:58
    
you don't need to log out and in, just source or . your .bash_profile –  glenn jackman Jun 1 '11 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. –  Warren Young Jun 2 '11 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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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