Updating the ~/.bashrc file for a script

I am developing a script that will configure and setup an ubuntu-desktop environment. One of the changes it makes is appending functions and other things to the ~/.bashrc file. Later in the script, I need to call one of the functions added to ~/.bashrc but I get the command not found error. Here is an example script:

# t.sh
#!/bin/bash
text='test-func() { echo It works!; }'
echo "$text" >> ~/.bashrc
source ~/.bashrc
test-func
echo checkpoint

Output:

./t.sh: line 10: test-func: command not found
checkpoint

I assumed sourcing ~/.bashrc would update the shell allowing me to call test-func but it does not. Googling around I found exec bash to replace source ~/.bashrc.

New Output:

./t.sh: line 10: test-func: command not found

From my understanding of exec, it just creates a new shell cutting the script off; therefore "checkpoint" is never printed out.

How can I update ~/.bashrc and run the updates in the same script?

Any help is much appreciated.

5

1 Answer

Actually, your .bashrc does get sourced. However, .bashrc is intended to be read by interactive shells. A shell that runs a script is not interactive.

In Ubuntu, .bashrc checks that the shell sourcing it is interactive, and otherwise stops execution. You should find this line towards the beginning:

# If not running interactively, don't do anything
[ -z "$PS1" ] && return

This causes your script to stop sourcing the file before it reads your function.

You can simply attach your function to another file than .bashrc and it should work fine. If you insist on using .bashrc, you could simply set the variable PS1 to some dummy value in your script before sourcing .bashrc.

7

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like