3

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.

2 Answers 2

2

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)

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

or directly in the bash FAQ:

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

3
  • 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. Jan 12, 2014 at 22:47
  • Can you please expand this A so that it explains what you're doing a bit? Thanks.
    – slm
    Jan 12, 2014 at 23:07
  • Just found out a relevant question and added it to my answer
    – lgpasquale
    Jan 12, 2014 at 23:19
1

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
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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