Introduction to Shell variable Programming

Source: Internet
Author: User
Tags line editor

• Shell programming: Shell Variables
1_1 system variable
Limit 2 Shell user Variables
■ 2.1 Basics
■ 2.2 tips
■ Array in 2.3 shell
Environment Variable 3 shell
Let's take a look at Shell variables instead of Shell versions. There are three variables in Shell: System variables, environment variables, and user variables. User variables are the most used in programming. System variables are used in parameter judgment and command return value judgment. environment variables need to be set when the program is running.

1. System Variables

There are not many common Shell system variables, but they are very useful, especially when detecting some parameters. The following are common Shell system variables.
Description
$ N $1 indicates the first parameter, and $2 indicates the second parameter...
$ # Number of command line parameters
$0 name of the current program
$? The return code of the previous command or function.
$ * Save all parameters in the form of "parameter 1 parameter 2 ..."
$ @ Save all parameters in the form of "parameter 1" "parameter 2 "...
$ PID of the Program (process ID)
$! PID of the previous command
$ N $ #$0 $? Take a look at the following example:

Copy codeThe Code is as follows :#! /Bin/sh
# This file is used to explain the shell system variable.
Echo "the number of parameter is $ #";
Echo "the return code of last command is $? ";
Echo "the script name is $0 ";
Echo "the parameters are $ *";
Echo "/$1 = $1;/$2 = $2 ";

The running result is as follows:
-Bash-2.05b $./chapter2.1.sh winter stlchina
The number of parameter is 2
The return
Code of last command is 0
The script name is./chapter2.1.sh
The parameters are winter stlchina
$1 = winter; $2 = stlchina
This example is too simple and not practical at all. Here is a practical example. If you don't understand it, it doesn't matter. I will explain it in detail later.Copy codeThe Code is as follows :#! /Bin/sh
If [$ #-ne 2]; then
Echo "Usage: $0 string file ";
Exit 1;
Fi
Grep $1 $2;
If [$? -Ne 0]; then
Echo "Not Found \" $1 \ "in $2 ";
Exit 1;
Fi
Echo "Found \" $1 \ "in $2 ";

In the preceding example, $0 $1 $2 $ #$? is used? And other variables. The following is an explanation of the program:
1. determine the number of running parameters. If the value is not equal to 2, "usage help" is displayed. $0 indicates that it is the script itself.
2. Use grep to search for the $1 string in the $2 file.
3. Determine the return value after the previous command is run (generally, 0 is returned for success, and non-0 is returned for failure ).
4. If the information is not displayed successfully, the information is not displayed. Otherwise, the information is displayed.
5. "/" indicates an escape character. If "still needs to be displayed, an escape character/" must be added /".
The following is an example:
./Chapter2.2.sh usage chapter2.2.sh
Not Found "usage" in
Chapter2.2.sh
-Bash-2.05b $./chapter2.2.sh Usage chapter2.2.sh
Echo
"Usage: $0 string file ";
Found "Usage" in
Chapter2.2.sh

2 Shell user Variables

2.1 Basics
No matter how many system variables there are, it is always not enough for demand. User variables are the most commonly used variables, which are also very simple to use.

A user-defined variable must consist of letters, numbers, and underscores. the first character of the variable name cannot be a number. Like other UNIX names, the variable name is case sensitive. you can assign values to user variables as follows:

Name = "Winter"
When referencing a variable, you must add the $ symbol before it. You can assign values to each other between variables, for example:

Name = "Winter"
WINTER = $ name
Echo
"Hello $ WINTER! "

The output result should be clear: Hello Winter!

Note that no space exists between the variable and '=', '=', or the value assignment. Otherwise, shell will not consider the variable as being defined. With the basic usage, you can start your programming work completely. However, sometimes it is necessary to plan ahead. The following describes some tips on user variables.

2.2 tips
You can also use variables and other characters to form a new word. In this case, you may need to include the variable with {}, for example:

SAT = Satur
Echo
Today is $ {SAT} day
The output result is: Today is Saturday.

Sometimes to avoid confusion between the variable name and other characters, you 'd better get into the habit of including the variable name.

For unassigned variables, Shell treats them with null values. You can also use the unset command to clear the value assigned to the variables. see an example:

Copy codeThe Code is as follows :#! /Bin/sh
Echo "a = $ ";
A = 2
Echo "a = $ ";
Unset
Echo "a = $ ";

First, guess what the result is?
-Bash-2.05b $./test
. Sh
A =
A = 2
A =
If you know C ++, you should know that there is a variable modifier "const", which is used to avoid the program from accidentally modifying the variable. In shell, you can use the same modifier "readonly" for user variables. If I modify the preceding example to this:Copy codeThe Code is as follows :#! /Bin/sh
Echo "a = $ ";
# Readonly is added below
Readonly a = 2
Echo "a = $ ";
Unset
Echo "a = $ ";

The results will certainly be different:
-Bash-2.05b $./test
. Sh
A =
A = 2
A = 2
2.3 array in shell
Array can also be set in shell variables, but different shell versions have different array assignment methods, while the bourne shell does not support array methods. Therefore, we recommend that you do not use arrays if you do not need them. If your data structure is very complex and you must use arrays, I suggest you select another language. shell is not omnipotent.

Shell has two ways to assign values. The first method is to directly assign values using Subscript:

Name [0] = "Tom"
Name [1] = "Tomy"
Name [2] = "John"
...
Another method is different for different shell versions. Assign values in bash:
[Code]
#! /Usr/local/bin/bash
Name = ("Tom" "Tomy" "John ")
For I in 0 1 2
Do echo $ I :$ {name [$ I]};
Done

[Html]
The above two assignment methods have the same effect. In addition, do you see the method for accessing array elements? Use $ {name [index. Note that the first line uses #! /Usr/local/bin/bash. The output result is:
-Bash-2.05b $./test
. Sh
0: Tom
1: Tomy
2: John

3. shell Environment Variables

Shell environment variables are accepted by all shell programs. When the shell program runs, it receives a set of variables, which are environment variables. Common environment variables:

Name Description
PATH Command search path, with the colon as the separator. Note that the current directory is not in the system path.
HOME The path name of the home Directory, which is the default parameter of the cd command.
COLUMNS Defines the length of the command line that can be used in the Command editing mode.
EDITOR Default Line Editor
VISUAL Default visual editor
FCEDIT Editor used by the command fc
HISTFILE Command history file
HISTSIZE Maximum number of commands that can be included in the command history file
HISTFILESIZE Maximum number of lines in the command history file
IFS Define the Separator Used by SHELL
LOGNAME User Login Name
MAIL Point to a file whose modification time needs to be monitored by SHELL. After the file is modified, SHELL sends You hava mail to the user
MAILCHECK SHELL checks the cycle of the MAIL file, in seconds
MAILPATH The function is similar to MAIL, but a group of files can be separated by colons. Each file can be followed by a question mark and a message sent to the user.
SHELL SHELL path name
TERM Terminal type
TMOUT The time when the SHELL exits automatically, in seconds. If it is set to 0, the SHELL exits automatically.
PROMPT_COMMAND Specifies the command to be executed before the main command prompt
PS1 Main Command Prompt
PS2 Second-level command prompt, which must be used for data input during Command Execution
PS3 Select Command Prompt
PS4 Debug Command Prompt
MANPATH Find the path to the manual page, separated by a colon
LD_LIBRARY_PATH Search for the library path, separated by colons

The most important of these variables is the PATH. Do you want to explain the importance of these variables?

If you want to make all other shell programs use the variables you define, that is, to define new environment variables. You only need to use the export keyword. For example:
Export
MY_NAME = Winter
Export
PATH =/home/winter/bin: $ PATH

In the above program, the first line outputs the MY_NAME variable, and the second line adds a PATH/home/winter/bin to the environment variable PATH. If you want these settings to be valid when you log on to unix/linux, you need to add them to your shell STARTUP script.

~ /. Bash_profile
In other versions, you can see it at a Glance. In your home directory ". files starting with "are generally hidden. You need to use the 'LS-al' command to display them.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.