What is a variable

Values stored under a fixed name that may change

  • Submit the script’s ability to adapt to changes in task requirements and operating environment
  • Easy to reuse in scripts

Variable classification

Custom variable

  • Define/assign variables

Variable name = variable value

[root~]# x=12
[root~]# y=13
Copy the code
  • Use the variable

Echo $variable name

[root~]# x=10
[root~]# echo $x
Copy the code
  • Cancel the variable

Unset the variable name

[root~]# unset x
Copy the code

The environment variable

It is defined by the system in advance and called directly when used

  • The configuration file

/etc/profile /root/.bash_profile

  • The relevant operation

-env: lists all environments. -set: lists all variables

  • Common environment variables
PWD Current location PATH PATH of the command program USER Current USER name HOSTNAME HOST name UID Current USER ID SHELL interpreter of the current USER HOST Home directory of the current USER PS1 Level-1 prompt PS2 Level-2 promptCopy the code

Predefined variable

– Saves the execution information of the script program

  • You cannot use these variables directly
  • You cannot assign values to these variables directly
$1 The first positional argument that follows when the script is executed $2 the second positional argument that follows when the script is executed $3 The third positional argument that follows when the script is executed $* The number of positional arguments that all positional arguments $# The random process number $? To determine whether the previous command succeeded, 0 indicates success and non-0 indicates failureCopy the code

Location variables

Command line arguments 1, 1, 1, 2, $3… (First parameter, second parameter, third parameter)

Variable expansion

Quotation marks and backapostrophes

  • Double quotes: Treat $as a variable
  • Single quotation marks: Treat $as a normal character
  • Backapostrophe: Takes the execution output of a command as a variable value

Read Input value

  • From read reads the variable from the keyboard to complete the assignment

    Format: read [-p ‘prompt ‘] Variable name

  • Terminal information

    – stty-echo: disables terminal output

    -stty echo: restores terminal output

Scope of a variable

  • A local variable

This parameter is valid only in the current shell environment and cannot be used in other shell environments

  • The global variable

Valid in all shell environments, local variables can be declared as global variables using export

A =100 export a // Publish existing variables as global effects export b=200 // Create global variables export-n a // Restore global variables to local variablesCopy the code