Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variables set in ~/.bashrc and accessing them in shellscript

Tags:

bash

I have this at the very top of my .bashrc, before the return for non-interactive shells

FOO="BAR"; export FOO
echo "HELLO WORLD"

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

I have a script test.sh in my homedirectory with this:

#!/bin/bash
echo "A"
echo $FOO
echo "B"

I execute test.sh. The output:

A

B

2 Questions:

  • Why don't I see the value of $FOO?
  • Why don't I see the "HELLO WORLD"?

edit: I thought the script with #!/bin/bash triggers a subshell which will call the .bashrc again, am I that wrong?

edit: Even If I do call the script from another host I won't see any values. Not even then , the .bashrc will be executed???

ssh remotehost "/home/username/test.sh"
like image 601
Preexo Avatar asked Jan 14 '23 02:01

Preexo


1 Answers

.bashrc is only sourced automatically for non-login interactive shells. Often, you would put . .bashrc near the beginning of your .bash_login file, to ensure that .bashrc is sourced for both login and non-login interactive shells.

.bashrc is not sourced automatically for non-interactive shells, such as those started when you execute a shell script.

Since you export FOO from .bashrc, the fact that test.sh sees FOO having a null value tells me that you are running the script from a login shell. Does echo $FOO from the prompt print BAR? I would be surprised if it did and test.sh did not.

like image 199
chepner Avatar answered Jan 19 '23 23:01

chepner