Try to grasp as much of what follows here as possible:
(Temporary) Bash Variables:
varName=value
Example# 1:
Code:
-bash-2.05b# logFile=/tmp/myLog
-bash-2.05b# echo $logFile
/tmp/myLog
Example# 2:
Code:
-bash-2.05b# maxWarnings=10
-bash-2.05b# echo $maxWarnings
10
Example# 3:
Code:
-bash-2.05b# developerName="Mr. Dev"
-bash-2.05b# echo $developerName
Mr. Dev
Those variables will not be available when your script terminates or login session is closed.
Persistent Bash Variables:
export variableName=value
Example# 4:
Code:
-bash-2.05b# export greetings="Have happy working hours, ${USER}."
-bash-2.05b# echo $greetings
Have happy working hours, root.
-bash-2.05b# cat > persVar.sh
#!/bin/bash
echo $greetings
-bash-2.05b# chmod +x persVar.sh
-bash-2.05b# persVar.sh
Have happy working hours, root.
Now decide on:
You want to use a persistent variable whenever
[1] any user logins (in the present and in the future as well)
[2] or only you login
Method# 1-A
edit /etc/profile
Insert the following line at an appropriate place or at the end of the file:
Code:
export greetings="Have happy working hours, ${USER}."
Method# 1-B
Code:
-bash-2.05b# echo 'export greetings="Have happy working hours, ${USER}."' >> /etc/profile
-bash-2.05b# tail -n 1 /etc/profile
export greetings="Have happy working hours, ${USER}."
Method# 2-A
edit the file
Code:
ls -l ~/.bash_profile
OR
Insert the following line at an appropriate place or at the end of the file:
export greetings="Have happy working hours, ${USER}."
Method# 2-B
Code:
-bash-2.05b# echo 'export greetings="Have happy working hours, ${USER}."' >> ~/.bash_profile
OR
Code:
-bash-2.05b# echo 'export greetings="Have happy working hours, ${USER}."' >> ~/.profile
Verify your work:
Code:
login as: demo
demo@linuxzoo.net's password:
[demo@host-6-41 demo]$ echo $greetings
Have happy working hours, demo.
[demo@host-6-41 demo]$
A note on .bash_profile or .profile versus .bashrc
When you login, your
.bash_profile or .profile file is executed which in turn first checks whether .bashrc exists or not. If it does, then it is first called:
Code:
[demo@host-6-41 demo]$ more .bash_profile
# .bash_profile
# Get the aliases and functions
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
That means that you can write your "permanent bash variables" in .bashrc after (preferably) "# User specific environment and startup programs" or in your .bash_profile (or .profile) file as shown earlier.
Code:
[demo@host-6-41 demo]$ more .bash_profile
# .bash_profile
# Get the aliases and functions
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
# User specific environment and startup programs
Feel free to play with both the files, but first take their backup:
Code:
cp .bashrc .bashrc-bk
cp .profile .profile-bk
Note: If you edit .profile or .bash_profile or .bashrc then you can bring the variables to life without having to relogin:
Code:
source .bash_profile
Cheers!
