Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Source bashrc from script failing

Tags:

bash

shell

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?

like image 892
bezi Avatar asked Sep 23 '26 16:09

bezi


2 Answers

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.)

like image 184
Jonathan Leffler Avatar answered Sep 26 '26 12:09

Jonathan Leffler


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.

like image 41
gpojd Avatar answered Sep 26 '26 12:09

gpojd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!