Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`source ~/.bash_profile` do not works inside a bash script

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?

like image 700
sensorario Avatar asked May 03 '18 13:05

sensorario


People also ask

What happens when you source a file in bash?

The source command reads and executes commands from the file specified as its argument in the current shell environment. It is useful to load functions, variables, and configuration files into shell scripts.

What is #!/ Bin bash in bash?

As we mentioned earlier,#!/usr/bin/env bash is also a shebang line used in script files to execute commands with the Bash shell. It uses the env command to display the environment variables present in the system and then execute commands with the defined interpreter.

What is ${ 0 in bash?

($0) Expands to the name of the shell or shell script. This is set at shell initialization. If Bash is invoked with a file of commands (see Shell Scripts), $0 is set to the name of that file.


2 Answers

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.

like image 100
jmkmay Avatar answered Sep 19 '22 00:09

jmkmay


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

like image 22
HardcoreHenry Avatar answered Sep 22 '22 00:09

HardcoreHenry