Detailed explanation of variables in Linux Shell

  • Define variables

Format 变量名=XXX. It should be noted that you must not type spaces before and after the equal sign when defining. The format of the variable name is similar to the C++, Java, etc. you have learned. Do not use special characters at the beginning.

#!/bin/bash
test="this is for test"
  • Use variables

When using a variable, you need to add it before the variable name 美元符号$. The more standard is ${变量名}(this method is used in the following, I hope you will get used to it). For example, when the echo function is used for output, if $ is not added, test will be output instead of the value corresponding to the variable test.

#!/bin/bash
test="this is for test"
echo ${
    
    test}

You only need to add $ when you use variables, and you don’t need to use $ when you re-assign variables. E.g

#!/bin/bash
test="this is for test"
echo ${
    
    test}
test="change test"
echo ${
    
    test}
  • Read-only variable

Through the readonly variable name, the variable cannot be reassigned

#!/bin/bash
test="aaa"
readonly test
test="bbb"

After running the script, an error will be reported /bin/sh: NAME: This variable is read only.

  • Delete variable

Use the unset 变量名delete variable, after deleting it can be output by echo, and the output result is a blank line.

#!/bin/bash
test="this is for test"
unset test
echo ${
    
    test}

Note that unset cannot delete variables that have been manipulated by readonly.

  • Variable type

When running the shell, there will be three types of variables:
1. Local variables. Local variables are defined in scripts or commands and are only valid in the current shell instance. Programs started by other shells cannot access local variables.
2. Environment variables are all programs. , Programs including shell holes can access environment variables, and some programs need environment variables to ensure their normal operation. Shell scripts can also define environment variables when necessary.
3. Shell variables Shell variables are special variables set by the shell program. Some of the shell variables are environment variables and some are local variables. These variables ensure the normal operation of the shell.
In other words, a shell variable contains one or more of the local variables, which can exist at the same time or one, depending on the function of the written shell program.

Guess you like

Origin blog.csdn.net/weixin_43716048/article/details/108825901