3

I've written a simple bash script that adds an alias to my .bashrc automatically, and when it finishes, I would like it to source the .bashrc

It works fine as of now, for example

./addalias.sh ls 'ls -l' 

properly appends 'alias ls='ls -l' to the .bashrc, but doesn't source it.

The code is as follows:

#!/bin/bash
FIRST=$1

SECOND=${2:-cd `pwd`}

echo alias $FIRST="'$SECOND'" >> /home/oscar/.bashrc
echo alias $FIRST="'$SECOND'"

source /home/oscar/.bashrc

That doesn't work, nor does running an alias ("sourcebash") to source the bash instead of the last line.

Any thoughts on how this could be fixed?

2
  • 2
    Unless I am mistaken, your script will fork a shell process and it is being sourced there. When the script is finished, any changes to that shell are gone too. I don't know of an any way around this, but maybe someone else can help. Commented Jul 12, 2012 at 18:08
  • Unrelated, you can replace the if statement with SECOND=${2:-cd `pwd`} Commented Jul 12, 2012 at 18:43

3 Answers 3

3

The shell that runs 'addalias.sh' does source the .bashrc file; it then exits. It does not and cannot affect the parent shell's environment.

You'd have to invoke the command as:

source ./addalias.sh ls 'ls --color=auto'

Or:

. ./addalias.sh ls 'ls --color=auto'

(Now fixed: And I'm not convinced that, even in a question, playing with sudo rm -fr /* is remotely sensible. There's too much risk of an idiot copying and not realizing.)

Sign up to request clarification or add additional context in comments.

2 Comments

That is true. Fixed, thanks. Is there perhaps a way to write a function that sources the .bashrc in all shells?
No; each shell is independent and would have to source the .bashrc separately.
1

Maybe you can make it a function or an alias instead of a bash script. Doing that might cause the changes to occur in the same shell.

Comments

0

i'd make an alias which calls this 'addalias' script, then sources the newly-modified file.

something like

alias really_add_alias="addalias.sh; . .bashrc"

4 Comments

It must be a function, otherwise the script wont not get its arguments (sourcing of .bashrc will)
Like this: addalias() { addalias.sh "$@"; . ~/.bashrc; }
And yes, put the function in your .bashrc too. And I would suggest you'd better add the aliases to some other file, not your .bashrc. Just to be on a safe side. Less to source from that addalias() function, too
The function does the same as the alias, still not sourcing it, though. It properly appends the text to the .bashrc

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.