PDA

View Full Version : *** how to set up a variable in Linux? ***



meili100
10-05-2007, 02:16 PM
I am a newbie. I know this is a little off-stream of programming, but it is the problem when I tried to program in linux. I wonder if there is a way to set up a variable, say $VAR = /home/root, so that I can use
cd $VAR
instead of
cd /home/root

CornedBee
10-05-2007, 02:55 PM
VAR=/home/root

Where you put it depends on various factors. The shell startup scrips are a good place. (In the case of bash they are .bashrc, .bash_profile and so on, in your home directory.)

But this specific example (home) is better solved by just doing
cd
and the variable HOME is already set to your home directory anyway.

brewbuck
10-05-2007, 03:07 PM
VAR=/home/root

Also, don't put spaces on either side of the equals sign. It won't work if you do that.


Where you put it depends on various factors. The shell startup scrips are a good place. (In the case of bash they are .bashrc, .bash_profile and so on, in your home directory.)

I typically put such things in .bashrc, because that is always parsed even by non-login shells. Commonly, xterm or other terminal emulators launch their shells as NON-login shells. Such shells do not process the profile, but instead depend on the profile variables already set by the parent shell.

What it boils down to is that changes you make in .profile or .bash_profile may not be visible until you log out of your X session and log back in. So... I always put stuff in .bashrc instead.

EDIT: And of course, you don't have to put variable definitions in EITHER location. You can do it directly at a command line, if you want.

meili100
10-05-2007, 03:25 PM
Thanks all. But what are the differences among .bashrc, .bashrc_profile, and .profile ?

meili100
10-05-2007, 03:56 PM
Got the answer:

startup files

These files contain the aliases and environmental variables made available to Bash running as a user shell and to all Bash scripts invoked after system initialization.
/etc/profile

systemwide defaults, mostly setting the environment (all Bourne-type shells, not just Bash [1])
/etc/bashrc

systemwide functions and aliases for Bash
$HOME/.bash_profile

user-specific Bash environmental default settings, found in each user's home directory (the local counterpart to /etc/profile)
$HOME/.bashrc

user-specific Bash init file, found in each user's home directory (the local counterpart to /etc/bashrc). Only interactive shells and user scripts read this file. See Appendix G for a sample .bashrc file.

logout file

$HOME/.bash_logout

user-specific instruction file, found in each user's home directory. Upon exit from a login (Bash) shell, the commands in this file execute.

matsp
10-05-2007, 04:34 PM
You may want to do "export var=value", as that will make the variable available for other processes too.

--
Mats