Simple shell Programming Shell variable Introduction _linux shell

Source: Internet
Author: User
Tags arrays modifier versions alphanumeric characters line editor


• Easy to understand Shell programming: Shell variables
◦1 System variables
◦2 Shell user variables
■ 2.1 Basic
■ 2.2 Tips for use
■ 2.3 Array in shell
◦3 shell environment variables
Let's not worry about the version of Shell. Let's take a look at Shell variables. There are three types of variables in Shell: system variables, environment variables, and user variables. Among them, user variables are used most in the programming process, system variables are used in parameter judgment and command return value judgment, and environment variables are mainly set when the program is running.

1 System variables

There are not many system variables commonly used by Shell, but they are very useful, especially when doing some parameter detection. The following are the commonly used system variables of Shell
Representation description
$ n $ 1 means the first parameter, $ 2 means the second parameter ...
$ # The number of command line parameters
$ 0 The name of the current program
$? 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" ...
$$ (process ID number) PID of this program
$! PID of the last command
Among them, the more used is $ n $ # $ 0 $?, Look at the following example:

The 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 following is the running result:
-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 one. If you don't understand it, it doesn't matter. There will be a detailed explanation in the following content.
The 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 above example, variables such as $ 0 $ 1 $ 2 $ # $? Are used. The following is an explanation of the program:
1. Determine the number of operating parameters. If it is not equal to 2, display and use "Usage Help", where $ 0 means the script itself.
2. Use grep to find the $ 1 string in the $ 2 file.
3. Determine the return value after the previous command is run (generally, success will return 0, and failure will return non-zero).
4. If there is no success, the relevant information is not found, otherwise it is found.
5. Among them, "" means escape, and "" must be displayed in "", then the escape character / "needs to be added.
The following running 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 Basic
No matter how many system variables there are, it is always not enough for demand. User variables are the most commonly used variables, and they are also very simple to use.
User-defined variables must consist of alphanumeric characters and underscores, and the first character of the variable name cannot be a number. Like other UNIX names, variable names are case-sensitive. For user variables, users can assign values as follows:

name = "Winter"
When referencing variables, you need to add the $ symbol in front, and users can also assign values between variables, such as:

name = "Winter"
WINTER = $ name
echo
 "Hello $ WINTER!"

The output should be very clear: Hello Winter!

One thing to note here: there should be no spaces between variables and '=', and no spaces between '=' and assignment, otherwise the shell will not think that the variable is defined. Mastered the basic usage method, you can start your programming work completely. But sometimes we need to plan ahead. Here are some tips for user variables.

2.2 Tips for use
Variables and other characters can also be used to form new words. In this case, you may need to enclose the variables in {}, such as:

SAT = Satur
echo
 Today is $ {SAT} day
The output is: Today is Saturday

Sometimes in order to avoid confusion between variable names and other characters, you'd better develop a habit of enclosing variable names in {}.

For unassigned variables, the shell treats them as null values. You can also use the unset command to clear the values assigned to the variables. See an example:

The code is as follows:

#! / bin / sh
echo "a = $ a";
a = 2
echo "a = $ a";
unset a
echo "a = $ 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" to prevent the program from accidentally modifying variables. In the shell, for user variables, you can use the same modifier "readonly", if I modify the above example to this:
The code is as follows:

#! / bin / sh
echo "a = $ a";
#Readonly added below
readonly a = 2
echo "a = $ a";
unset a
echo "a = $ a";

The result will of course be different:
-bash-2.05b $ ./test
.sh
a =
a = 2
a = 2
2.3 Arrays in the shell
Arrays can also be set in shell variables, but different shell versions have different array assignment methods, and array methods are not supported in the bourne shell. Therefore, if it is not very necessary, it is recommended that you do not use arrays. If your data structure is very complicated, you must use an array, then I suggest you choose another language, the shell is not a panacea.
The shell has two assignment methods. The first is to directly assign values using subscripts:

name [0] = "Tom"
name [1] = "Tomy"
name [2] = "John"
...
The other way is different for different shell versions. Assignment 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 achieve the same effect. In addition, do you see a way to access array elements? Use $ {name [index]}. Note that the first line uses #! / Usr / local / bin / bash, which is different from the previous one. The output is:
-bash-2.05b $ ./test
.sh
0: Tom
1: Tomy
2: John

3 shell environment variables

Shell environment variables are parameters that all shell programs will accept. When the shell program is running, it will receive a set of variables, which are environment variables. Commonly used environment variables:

Name Description
The PATH command searches the path, with a colon as the delimiter. Note that unlike DOS, the current directory is not in the system path
The path name of the HOME user home directory, which is the default parameter of the cd command
COLUMNS defines the length of the command line that can be used in command editing mode
EDITOR default line editor
VISUAL default visual editor
Editor used by FCEDIT command fc
HISTFILE command history file
The maximum number of commands that can be included in the HISTSIZE command history file
The maximum number of lines in the HISTFILESIZE command history file
IFS defines the separator used by SHELL
LOGNAME user login name
MAIL points to a file that requires SHELL to monitor its modification time. When the file is modified, SHELL will send a message You hava mail to the user
MAILCHECK SHELL checks the period of the MAIL file in seconds
The MAILPATH function is similar to MAIL. However, a group of files can be used, separated by a colon, each file can be followed by a question mark and a message to the user
The path name of SHELL SHELL
TERM terminal type
The time for TMOUT SHELL to automatically quit, in seconds, if set to 0, it will prohibit SHELL from automatically quitting
PROMPT_COMMAND specifies the command that should be executed before the main command prompt
PS1 main command prompt
PS2 second-level command prompt, used when data input is required during command execution
PS3 select command prompt
PS4 debug command prompt
MANPATH Find the path of the manual page, separated by a colon
LD_LIBRARY_PATH The path to find the library, separated by a colon

Of these variables, the PATH is the most concerned about, the importance of which I do not say?

If you want to make the variables you define available to all other shell programs, that is, define new environment variables. You only need to use the export keyword. E.g:
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 effective when you log in unix / linux, you need to add them to your shell startup script, if you use bash

~ / .bash_profile
You can see other versions 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.