1

I'm trying to make a bash script to pipe a new alias to .bash_aliases and then source .bashrc:

#!/bin/sh
FIRST=$1
SECOND=${2:-cd `pwd`}

if [ -z $1 ]
then
    cat ~/.bash_aliases # no arg, show aliases
else
    echo alias $FIRST="'$SECOND'" >> ~/.bash_aliases
    . /home/andreas/.bashrc
fi

The . /home/andreas/.bashrc part doesn't work.

Following this I've tried running the script this way source . ./myscript.

And following this I've tried adding PS1='foobar' to the script before the . /home/andreas/.bashrc line.

Neither works.

2 Answers 2

3

When you say "doesn't work", I assume you mean that it doesn't actually put the alias in your interactive shell. That's because this script runs in a subshell. When you source .bashrc, it installs the aliases in the subshell. Then the subshell exits, and you return to your interactive shell. There is no way to modify the environment of a parent shell from a subshell.

That said, if this code ran from a function in your parent shell, instead of in a subshell, you'd be all set. Put this function in your .bashrc

function addalias
{
    FIRST="$1"
    shift
    SECOND="$@"

    if [ "${FIRST}" == "" ]
    then
        cat ~/.bash_aliases
    else
        echo alias "$FIRST"="$SECOND" >> ~/.bash_aliases
        alias "$FIRST"="$SECOND"
    fi
}
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect! Just need clarification: what does the shift line do?
Ahh. shift discards the first parameter, so that $@ now expands to the remainder of the parameters. It's an easy way to say parameters 2 through N. This way your alias command can have multiple words on the command line without having to quote them
1

That's because you are running this script in a separate shell process. The . command does work, but then the script exits and your current shell has not been altered at all.

Put this script into a function in your ~/.bash_aliases file. That way your current shell will be updated.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.