"Learn Linux with older boys Koriyuki Shell Programming"-Chapter II the Core foundation of shell variables

Source: Internet
Author: User
Tags define local echo b echo command

This article focuses on the core foundations of shell variables.

1. What are the variables?

What is a variable? Many people may not understand, simply put, a variable is a fixed string (or possibly a combination of characters, numbers, etc.) instead of more, more complex content, the content may also contain variables, paths, strings and other content.

Variables are assigned by: Write the name of the variable, followed by the "=" character, and finally the value, no space in between (the contents of the variable is generally enclosed in double quotes to prevent errors, especially when there are spaces between the contents of the values).

How do i print a variable? The value of the variable is printed by the echo command plus the $ variable name:

For example: Define variables and print variables:

[[email protected] ~]# xiaoyu= "My name is Xiaoyu" ==> defines the variable named Xiaoyu, the contents of the variable are:"My name is Xiaoyu"

[[email protected] ~]# echo $XiaoYu ==> print variable Xiaoyu value
My name is Xiaoyu

2. Types of variables:

Variables can be divided into two categories: environment variables (global variables) and ordinary variables (local variables)

(1) Environment variables can also be called global variables, which can be used in the shell in which they are created and in any process shell that they derive from, and can be divided into custom environment variables and bash built-in environment variables.

    • Environment variables generally refer to variables exported with export built-in commands that define the shell's operating environment and ensure proper execution of the shell commands. The shell uses environment variables to determine the login user name, command path, terminal type, login directory, and so on, all environment variables are system global variables and can be used in all child processes.

    • environment variables can be set and created on the command line, but the values of these variables are lost when the user exits the command row, and if you want the variable to be permanent, you can use the. bash_profile or. BASHRC or global profile/ETC/BASHRC or/etc/in the user's home directory. The profile file is defined.

    • The names of all environment variables are capitalized in accordance with the system specification. Before you apply an environment variable to a user process program, you should export the definition with the Export command, for example: Export xiaoyu=1.

    • Query the environment variables in the system: set (output all variables, including global variables and local variables), env (global variables only), declare (Show all variables, functions, integers, and exported variables).

(2) Common variables can also be referred to as local variables and can only be used in shell functions or shell scripts that create them.

3. Custom Environment variables:

Setting the environment variable, after assigning a value to the variable or using the Export command when setting the variable, actually out of the export command, the declare built-in command with the-X option can do the same. The Export command and the declare command are in the following format:

(1) Export variable name =value

(2) Variable name =value;export variable name

(3) Declare-x variable name =value

Here's how to define variables and assign values:

[Email protected] ~]# export Name=xiaoyu
[Email protected] ~]# Declare-x Name=xiaoyu
[Email protected] ~]# Name=xiaoyu;export NAME

The following is an example of a custom Global environment variable:

[Email protected] ~]# Cat/etc/profile | grep Xiaoyu
Export name= ' Xiaoyu ' ==> Edit file/etc/profile,add row, save exit

[Email protected] ~]# source/etc/profile ==> or. /etc/profile make /etc/profile effective

[[email protected] ~]# echo $NAME ==> print variable

[Email protected] ~]# env | grep Xiaoyu ==> View the results of the definition

4. configuration file for which the environment variable is permanently active:

(1) User's environment variable configuration:

[[email protected] ~]# LS/ROOT/.BASHRC ==> recommended precedence in this file
[Email protected] ~]# Ls/root/.bash_profile

Tip: For the user's environment variable settings, the more common is the user home directory of . BASHRC and . Bash_profile.

(2) configuration file for Global environment:




To initialize or display the loaded content after login, place the script file in the /etc/profile.d/ directory (no execute permission required)

5. Two ways to set the sign-in prompt:

Method One: Add a string to the hint in/ETC/MOTD:

[Email protected] ~]# CAT/ETC/MOTD
Welcome to ...

Method Two: Add the following script below/ETC/PROFILE.D:

[[email protected] ~]# cat/etc/profile.d/welcome.sh ==> script content written according to the actual situation

6. Display and cancel environment variables:

(1) Print the variable via the Echo or printf command:

[Email protected] ~]# echo $NAME
[[email protected] ~]# printf "$NAME \ n" ==>printf is a more complex tool for formatting printed content, and generally does not require

(2) Display the default environment variables with env or set

(3) unset cancel local variables and environment variables:

[Email protected] ~]# echo $NAME
[Email protected] ~]# unset NAME
[Email protected] ~]# echo $NAME
==> return result is empty

Environmental Variables Knowledge Summary:

    • Variable names are usually capitalized.

    • Variables can be used in their own shells and sub-shells.

    • Export is commonly used to define environment variables.

    • Perform env by default to display all environment variable names and corresponding values

    • Output with "$ variable name", Cancel with "unset variable name"

    • When writing Crond timed tasks, be aware that the environment variables used by the scripts are best redefined in the shell scripts that are executed.

    • If you want the environment variable to take effect permanently, you can put it in the user environment variable file or the Global environment variable file.

7. Common variables:

(1) Define local variables: Local variables are used in scripts for the user's current shell lifetime.

Definition of common variables:

Variable name =value ==> assignment without quotation marks

Variable name = ' value ' ==> add single quotation mark when assigning value

Variable name = "Value" ==> with double quotation marks when assigning a value

The contents of a variable can be enclosed in single or double quotation marks or in quotation marks, but the meanings of the three are different.

Assigns the contents of a contiguous normal string to a variable, regardless of whether it is used without quotation marks, or whatever the quotation marks are, what the content is, and what it will output when the variable is printed.

Example: Define variables A, B, C, and print out the values of each variable.

[Email protected] ~]# a=
[Email protected] ~]# b= ' '
[Email protected] ~]# c= ""
[Email protected] ~]# echo a= $a
[Email protected] ~]# echo b= $b
[Email protected] ~]# echo c= $c
[[email protected] ~]# echo C=${c}

Hint: The $ variable name represents an output variable, which can be used in both $c and ${c}

Then the result of the above variable, continue to enter the following content:

[Email protected] ~]# a=$a
[Email protected] ~]# b= '$a '

[Email protected] ~]# c= "$a"
[Email protected] ~]# echo $a
[Email protected] ~]# echo $b$a
[Email protected] ~]# echo $c

The above case shows that when the content is a simple continuous number, string, pathname, the definition of variables in the case without quotation marks, the value of the variable will be parsed and then output;

When you define a variable, if you use single quotation marks, what is the content of the variable, and what is the output, what is WYSIWYG. Double quotes are used when defining variables, and variables and commands in quotation marks are parsed and then output when the contents of the variable are output.

Hint: The variable definition of the digital content can be without quotation marks, the other is not specifically required to define a string, such as the best to add double quotation marks, if you need to output the same as the single quotation mark, the definition of variable double quotation marks is the most common usage scenario.

(2) The requirement to define variable names and variable content assignments in the shell:

Variable names generally consist of letters, numbers, underscores, and can begin with a letter or underscore.

(3) The method of assigning the result of a command as the content of a variable:

Method One: Variable name = ' ls '

Method Two: Variable name = ' $ (LS) '

Experience summary of local (normal) variable definition and assignment:

Define variables:

    • If the content of a variable is a sequential number or string, the contents of the variable can be unquoted without quotation marks when the value is assigned.

    • When a variable has a lot of content, double quotes are added if there are spaces and you want to parse the variables in the content.

    • Single quotes are used when you want the contents of the variable to be output as-is.

    • When you want the contents of a variable, the parse result of the command is enclosed in a backslash or $ ().

Output variables:

    • Use "$ variable name" to output the contents of the variable, commonly used "echo $ variable name" way, of course, can also be used instead of the echo output more complex format content.

    • The value of the variable can be obtained by adding $ before the variable name, $a and ${a} are different, but the effect is the same.

    • When you output a variable with the echo command, you can also use single quotes, double quotes, no quotes, such as echo$a, echo "$a", echo ' $a ', and the summary of the previous variable content definition is consistent.

    • $dbname _tname, when there are other strings attached to the variable, you must enclose the variable with curly braces {}, for example:$dbname _tname is changed to ${dbname}_tname.

8. In the definition of variables, assignments and variable output plus single quotation marks, double quotes, anti-apostrophes and non-quoted brief description.

Single quotation marks
What you see is what you get, that is, when you export everything inside a single quote as it is, or what you see in a single quotation mark, what you output.
Double quotes
Output double quotation marks, if there are commands in the content (to be caused by the inverse apostrophe), variables, special escape characters, etc., the variables, commands, escape characters will be resolved first, and then output the final content, recommended to use.
No quotation marks
Assigning a value, if there are spaces in the variable contents, will result in an incomplete assignment. When the output content, the string containing the space is treated as a whole output, if there are commands in the content (to be caused by a backslash), variables, etc., it will first parse the variables, commands, and then output the final content, if the string with special characters such as spaces, it may not be fully output, so you need to add double quotation marks. Generally contiguous strings, numbers, paths, etc. can be assigned and output without any quotation marks, but it is best to use double quotes instead of unquoted cases, especially when assigning values to variables.
"is typically used to refer to a command, which executes when the command is executed, equivalent to $ (), the assignment and the output are to be caused by the command."

Tip: The above conclusions also apply to grep, awk.

This is only the conclusion of the Linux shell, which is a bit special for the awk language.

awk invokes the shell variable with the following conclusions:

650) this.width=650; "Width=" "height=" 109 "title=" Awk.png "style=" WIDTH:400PX;HEIGHT:74PX; "alt=" Wkiom1j1tl7yqhkpaaaryuf4p3q797.png "src=" https://s5.51cto.com/wyfs02/M00/91/61/ Wkiom1j1tl7yqhkpaaaryuf4p3q797.png "border=" 0 "vspace=" 0 "hspace=" 0 "/>


    • When defining a normal string variable in a script, you should try to enclose the contents of the variable in double quotation marks.

    • The contents of a simple numeric variable can be unquoted.

    • You want the contents of a variable to be output as it is, with single quotation marks.

    • Use the inverse quotation mark (backslash) or $ () when you want the variable value to refer to the command and get the result of the command.

8. Recommendations for customizing common string variables:

    • When the content is a purely numeric, simple sequential character (without any spaces in the content), it can be defined without any quotation marks.

    • In the absence of special circumstances, strings are always defined with double quotation marks, especially if there are spaces in the middle of multiple strings.

    • Use single quotation marks when the contents of a variable need to be output as-is.


(1) Variable name and variable content definition summary:

A) variable names can only be letters, numbers, or underscores, and can only start with letters or underscores.

b) The definition of the variable name should be a certain norm, and to be known.

c) General variable definitions, commonly used double quotation marks, simple continuous string can be unquoted; The single quotation mark that you want to output as is.

D) If you want the contents of the variable to be the result of parsing the command, use the back quotation marks (the inverse apostrophe), or enclose the command with $ () to assign the value.

(2) Shell defines variables with "=" knowledge

You can use "=" or "= =" When comparing variables for equality.

(3) Print output and knowledge of using variables

A) to print out or use a variable, the variable name is preceded by the $ symbol, and the variable name immediately after the other character, you want to enclose the variable part in curly braces, in the unset, Export, (()) and other scenarios, but do not print the variable is not added $.

b) When printing output or using variables, usually double or no quotation marks, if it is a string variable, it is best to double quotation marks, you want to output the same as the single quotation mark.

Above for I read "with the old boy learn Linux Yun Koriyuki Shell programming Combat" This book when the note, if there is any copyright issues, please contact [email protected].

This article is from the "shayatou_1990" blog, make sure to keep this source http://shayatou1990.blog.51cto.com/12806916/1917018

"Learn Linux with older boys Koriyuki Shell Programming"-Chapter II the Core foundation of shell variables

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.