9

This is a script that move a bash file into homepage and load it with source command.

# update.sh
#!/bin/bash
cp -f $PWD/bash_profile ~/.bash_profile
source ~/.bash_profile

It does not work! It update file with cp -f $PWD/bash_profile ~/.bash_profile.

Inside ~/.bash_profile there is a new PS1 definition. File is updated but no changes happened until new window is opened. I need to run source ~/.bash_profile after script execution ...

Is it possibile to run source command inside bash script?

4
  • You need to source the bash script if you want it to update your current shell. Commented May 3, 2018 at 13:46
  • It's possible, but useless for the same reason you are using source inside the script instead of executing .bash_profile. Commented May 3, 2018 at 13:53
  • The shebang must be the first line in the file. Commented May 3, 2018 at 14:44
  • Not a new answer, but some clarification. When you echo "PS1=${PS1}" after source ~/.bash_profile, you will see it is changed. The changes get lost, when your script update.sh` is finished. You can use source to keep the changes valid in your current shell. Commented May 7, 2018 at 21:42

2 Answers 2

14

From MangeshBiradar here:

Execute Shell Script Using . ./ (dot space dot slash)

While executing the shell script using “dot space dot slash”, as shown below, it will execute the script in the current shell without forking a sub shell.

$ . ./setup.bash

In other words, this executes the commands specified in the setup.bash in the current shell, and prepares the environment for you.

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

3 Comments

sorry still not able to execute source ~/.bash_profile from within bash script
This was the only solution that works for me. Even starting a new shell (executing: bash) after I sourced the file didn't work.
Sorry but this is not clear to me.. this solution is meant to go in .bash_profile? So the command in .bash_profile would be source ". ~/script.sh"? This does not seem to work. An applied example would be nice
3

The bash script runs in its own instance of the shell. When the shell exits, all environment variables of that new shell (including your PS1) are forgotten. Note: this is a security consideration -- if a shell could change the environment of it's caller, it could very easily do some serious damage to that user by aliasing various commonly used commands.

If you run source update.sh though, it will run the commands as if the user typed them in on their own. (or you could do as @JonathanMay suggested using the ., which does the same thing).

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.