Variables,
All variables are identical and do not need to be declared on initialized before they can be used. You can use any alphanumeric string to make up your variable name. Depending on the use, there are 2 ways to reference it:
- Assignment-- If you are assigning data to a variable, you reference the variables directly by its name. For example , if you want to assign "John" to the variable, name, It would be like this :
It doesn't have to be with quotes (""). But if there are white-space characters, then you have to.name="John"
name=John
name="John Doo"- Value-- When you want the contents of a variable, you must prefix the name of the variable with a $ in order to tell the shell that you want the value of the variable returned. Like this
$name
.
You can also place it between {}. Example:mv $file ${file}1
export
Most variables that you use only need to be used in the instance of the shell that you declare them - these variables are called local variables and are the default type in bash.
Sometimes, however, you may need to start scripts from within scripts and have data accessible between the several different running shell scripts. You can do this by creating an environment variable in your script. An environment variable is valid for any shells that are started under the shell in which it is defined. To create an environment variable from an existing variable, you can use the command export. To turn thename
variable into an environment variable, you would type:Once the shell or script that defined an environment variable exits, the contents of the variable is lost.export name
There are some variables already defined for you:
$0 The name of the shell-script that is being executed. $# The number of arguments/parameters. $1 The first argument. $2 The second argument, you can guess the third. $var[i] The i argument, Can be greater then 10. $$ The pid of the shell-script. $USER Username of the user who is executing the script. $HOME The home director of the current user. $PATH List of directories, separated by :. $PS1 Command prompt, usually $ $PS2 A second command prompt, used for more input, usually > $IFS A list of separating signs, that can be used when the shell reads input. ${var} value of var, insulate var string $var[n-m] words n through m from var word-list, though n and m can both be absent and default to 1 and $#var resp. $< Substitute line from stdin (interactive input) $(command) Another way of executing a command, replaces $var=`command`