Variables in Shell Scripts


As a programming language, shells can process variables in your scripts. Following are the three types of variables shell scripts you can work with:

  • Environment variables are part of the system, and you worked with two of them, Aliases and PATH, in the previous example. You can define new environment variables, and some environment variables (like Alias and PATH) can be modified in a script.

  • Built-in variables, like command switches, are provided by the operating system and cannot be modified.

  • User variables are defined and used by the script writer.

Note

If you have experience with other programming languages, you'll notice one difference with shell programming: variables are not typed in shell scripts.

Conversely, if you learn shell scripting first and go on to other programming languages, you will need to learn how to identify variables as numbers, strings, or other data types that exist in that language.


Assigning Values to Variables

Declaring and initializing variables in bash is straightforward. To use a variable called lcount to count the number of iterations in a loop, type lcount=0.

To store a string in a variable, just declare and identify:

myname=mikemc 

If the string has embedded spaces, use quotes:

myname="Michael McCallister" 

Accessing Variable Values

Access the value of a variable by prefixing the variable name with a dollar sign ($). To display your search path, for example, use $PATH. If the variable you want to access is var, use $var.

To assign the value of var to the lcount variable, type

lcount=$var 



SUSE Linux 10 Unleashed
SUSE Linux 10.0 Unleashed
ISBN: 0672327260
EAN: 2147483647
Year: 2003
Pages: 332

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net