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'd like an alias that additionally appends itself to ~/.bashrc, e.g.

function tailias
{
    $(echo "alias $1='${*:2}'" | tee -a ~/.bashrc)
}

I'm using tee to split the command to ~/.bashrc while leaving the stdout intact to be run by $().

This works fine for aliasing one-word commands, e.g.

[/home/acheong87] tailias f g
[/home/acheong87] alias
alias f='g'

and I see it appended to my ~/.bashrc. But for commands with spaces, I get

[/home/acheong87] tailias ll 'ls -al'
-bash: alias: -al: not found

It looks correct in ~/.bashrc

alias ll='ls -al'

—but in the alias list I get this crazy thing:

[/home/acheong87] alias
alias ll=''\''ls'

I've tried putting the quotes in different places, to no avail. I've reduced the function to just the echo, and like in the ~/.bashrc, it looks correct—so I can't figure out what hidden step is averting my attention.

share|improve this question

2 Answers 2

up vote 2 down vote accepted

You can eval to achieve what you want:

function tailias
{
    eval $(echo "alias $1='${*:2}'" | tee -a ~/.bashrc)
}

This is better expained in this question (where an alternative solution is given)

http://stackoverflow.com/questions/11079342/execute-command-containing-quotes-from-shell-variable

or directly in the bash FAQ:

http://mywiki.wooledge.org/BashFAQ/050

share|improve this answer
2  
Thanks! Could you perhaps explain why I'm seeing the behavior I'm seeing, however? Or, why eval fixes the problem? I'd like to understand the internals as much as I can. –  Andrew Cheong Jan 12 at 22:47
    
Can you please expand this A so that it explains what you're doing a bit? Thanks. –  slm Jan 12 at 23:07
    
Just found out a relevant question and added it to my answer –  lgpasquale Jan 12 at 23:19

Instead of using eval and tee to execute the command twice to add both a temporary alias and permanent alias in ~/.bashrc, you can simply reload the ~/.bashrc file after it is appended, which will update the alias list.

function tailias
{
    echo "alias $1='${*:2}'" >> ~/.bashrc && source ~/.bashrc
}
share|improve this answer
    
Thanks—definitely another valid way to do it. –  Andrew Cheong Jan 13 at 5:53

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.