[Linux Basics and Shell Scripts] The use of variables in Shell scripts

1. Basics of Shell variables

1.1 What are variables

In programming languages, a variable is a place to store a value. You can think of a variable as a storage box. You can put anything in it and when you need it, you can retrieve it by the variable name. Variables can contain letters, numbers, and underscores, but variable names must start with letters or underscores.

In the Shell, variables do not have data types. The value of a Shell variable is a string, regardless of whether the string is a number, a character, or even if the string contains extra spaces or other special characters.

1.2 How to define and use variables in Shell

In the Shell, you can use the equal sign =to define variables. Note that there cannot be spaces on both sides of the equal sign, which is specified by Shell syntax. Here is an example of defining a variable:

name="John Doe"

In this example, we define a namevariable called with the value "John Doe".

When using variables, you need to add $the symbol in front of the variable name. For example, we can print out namethe value of the variable :

echo $name

This line of command will output "John Doe". Note that when you reference an undefined variable, the shell treats it as an empty string.

You can also use unsetthe command to delete a variable:

unset name

After executing the above command, the variable namewill be deleted. If you try to print its value, you won't get any output.

2. Shell environment variables

2.1 What are environment variables?

Environment variables are an important part of Linux and other Unix-like operating systems. They are special variables that store system state or shell session information. For example, HOMEan environment variable stores the path to the current user's home directory, and PATHan environment variable stores a list of paths where the system should look for binary files when executing a command.

Environment variables are shared between shell sessions and their child processes. That is, the environment variables you define in the parent shell can be used in all child shells it starts.

2.2 The difference between environment variables and ordinary variables

The main difference between environment variables and ordinary variables is their visibility and life cycle.

  • Visibility: Ordinary variables are only valid in the current shell session, child shells will not inherit these variables. Environment variables can be shared between the parent shell and all child shells.

  • Life cycle: The life cycle of ordinary variables is only during the current Shell session. When the session ends, the variables will disappear. However, after an environment variable is defined, it will always exist unless explicitly deleted.

2.3 How to view, set and delete environment variables

You can use the envor printenvcommand to view environment variables. For example:

printenv PATH

This command will print out PATHthe values ​​of environment variables.

To set environment variables, you can use exportthe command. For example:

export VARNAME="value"

This command creates an VARNAMEenvironment variable named with the value "value". This variable will be valid in the current shell session and its subsessions.

To delete environment variables, you can use unsetthe command. For example:

unset VARNAME

This command will delete VARNAMEthe environment variables. It should be noted that this command will only delete variables in the current Shell session. It will not affect variables with the same name in other Shell sessions.

3. Shell positional parameters

3.1 What are positional parameters?

In shell scripts, positional parameters are special variables that represent the values ​​of command line parameters. For example, if your script is named , myscript.shand you run it ./myscript.sh arg1 arg2 arg3, then arg1, is the positional parameter.arg2arg3

The Shell will automatically assign these parameters to special variables $1, $2, $3, and so on. In this example, $1the value of is arg1, $2the value of is arg2, and $3the value of is arg3.

3.2 How to use positional parameters in scripts

In Shell scripts, you can use positional parameters directly through variables such as $1, $2, $3and so on. These variables represent the parameters you pass when executing the script.

For example, let's say you have a script myscript.shthat reads:

#!/bin/bash
echo "第一个参数是: $1"
echo "第二个参数是: $2"
echo "第三个参数是: $3"

Then you run the script ./myscript.sh apple banana cherryand the output of the script will be:

第一个参数是: apple
第二个参数是: banana
第三个参数是: cherry

3.3 Practical application examples of positional parameters

Positional parameters are useful in many scenarios. For example, you might have a script that requires the user to enter one or more file names as parameters and then operates on those files. You can use positional parameters to get these file names.

Here is a simple example script that accepts a file name as an argument and prints out the line number of the file:

#!/bin/bash
if [ -f "$1" ]; then
    echo "$1 的行数为:"
    wc -l "$1"
else
    echo "文件 $1 不存在"
fi

In this script, $1represents the file name entered by the user. -fThe test checks whether the file exists and wc -lthe command counts the number of lines in the file.

4. Shell special variables

4.1 Introduction to special variables in Shell

The Shell has some special variables with special meanings and functions. The following are some common Shell special variables:

  • $0: The value of this variable is the file name of the current script.
  • $#: The value of this variable is the number of positional parameters passed to the script.
  • $*: This variable is a list of all positional parameters. If you surround it with double quotes, "$*"then all positional parameters will be treated as a string.
  • $@: This variable is also a list of all positional parameters. However, if you surround it with double quotes, "$@"then each positional argument is treated as a separate string.
  • $$: The value of this variable is the process ID (PID) of the current Shell process.
  • $?: The value of this variable is the exit status of the last executed command. If the command executes successfully, the exit status is 0. If the command fails, the exit status is non-zero.

4.2 Functions and uses of special variables

Special variables have many uses in shell scripts. Here are some examples:

  • Use $0to print out its own filename in a script. This is useful in debugging and logging.

  • Use $#can be used in scripts to check that the user has provided the correct number of arguments. For example, if your script requires two parameters, you can use if [ $# -ne 2 ]to check whether the user provided both parameters.

  • Use $*and $@to iterate over all positional parameters in a script. $*and $@behave slightly differently, especially if you surround them with double quotes.

  • Use $$to get the PID of the current shell process in a script. This is useful when you need to create unique temporary file names or check if a process is running.

  • You can use $?in a script to check whether a command executed successfully. This is useful in error handling and debugging.

5. Shell variable operation

5.1 How to operate Shell variables

In the Shell, you can perform various operations on variables, such as assignment, string concatenation, substring extraction, and length calculation, etc.

  • Assignment: You can use the equal sign =to assign a value to a variable, for example var="Hello, World!".

  • String concatenation: You can use double quotes "..."to concatenate multiple strings or variables together, for example greeting="Hello, $name!".

  • Substring extraction: You can ${var:offset:length}extract a substring using , where offsetis the starting position (counting from 0) and lengthis the length of the substring.

  • Calculate length: You can ${#var}calculate the length of a string using .

5.2 Example demonstrations of string interception, length calculation, etc.

Here are some examples:

  • String concatenation:

    name="John"
    greeting="Hello, $name!"
    echo $greeting
    

    This script will print "Hello, John!".

  • Substring extraction:

    str="Hello, World!"
    echo ${str:7:5}
    

    This script will output "World". The starting position of the substring is 7 and the length is 5.

  • Calculate the length:

    str="Hello, World!"
    echo ${
          
          #str}
    

    This script will output "13", which is the length of the string "Hello, World!".

6. Scope of variables

6.1 The difference between global variables and local variables

In the Shell, variables are global by default. This means that variables you define anywhere in the script can be used anywhere in the script. This is included inside the function.

However, you can also define local variables. Local variables are only valid within the function in which they are defined. You can localdefine local variables inside a function using the keyword. Once the function returns, the local variables are destroyed.

The main difference between global variables and local variables is their scope:

  • The scope of global variables is the entire script. This means you can access global variables from anywhere in your script.

  • The scope of local variables is limited to the function in which they are defined. This means that you can only access local variables inside the function in which they are defined.

6.2 Correct way to use variables in functions

When you use variables within a function, you should try to use local variables unless you really need to access the variable outside the function. Using local variables can help you avoid naming conflicts and make your functions easier to understand and test.

Here is an example showing how to define and use local variables in a function:

function greet {
    
    
    local name=$1
    echo "Hello, $name!"
}

greet "John"

In this function, nameis a local variable. $1is the first parameter of the function. This function will print "Hello, John!".

If you try to access it outside the function name, you will get a null value because nameis local and only greetvalid inside the function.

Guess you like

Origin blog.csdn.net/weixin_52665939/article/details/131525868