Article directory
1. Shell script
1.1 Definition and purpose
Shell script is a script program composed of Shell commands. Shell is a command interpreter that provides a user interface in which users can type commands, which are then sent to the operating system for execution by the Shell. Shell scripts are widely used to automate tasks such as system management tasks, file operations, and program execution.
1.2 Create and execute Shell scripts
To create a shell script, you simply create a text file containing the commands you want to execute. This file can be created using any text editor such as vi, nano or emacs. Then save this file as .sh
a file. For example, myscript.sh
.
sh myscript.sh
The most common way to execute a shell script is to type or at the command line bash myscript.sh
. But before executing, you need to ensure that the script has executable permissions, which can be chmod +x myscript.sh
added via .
1.3 Basic structure of Shell script
A basic shell script contains the following parts:
-
The beginning of the script (shebang): This is a line starting with "#!" followed by the path to the shell that interprets this script. For example,
#!/bin/bash
it means that this script should be executed by bash. -
Comments: In a shell script, anything after the "#" symbol will be considered a comment unless it is at the beginning of a line and is followed by a "!" (i.e. shebang).
-
Commands and statements: This is the main part of the Shell script and contains all the commands and statements to be executed.
1.4 Example: A simple shell script example
Here is a simple shell script example:
#!/bin/bash
# 这是一个简单的shell脚本
echo "Hello, World!"
This script will print "Hello, World!".
1.5 Control structure of shell script
Shell scripts provide a variety of control structures, including conditional statements and loops.
-
Conditional statements: for example, if and case. The following is an example of an if statement:
#!/bin/bash if [ "$1" = "Hello" ] then echo "Hello, how are you ?" else echo "Sorry, I do not understand" fi
This script will check if the first command line argument is "Hello", if so, it will print "Hello, how are you?", otherwise, it will print "Sorry, I do not understand".
-
Loops: For example, for and while. The following is an example of a for loop:
#!/bin/bash for NAME in John Paul Ringo George do echo "Hello, $NAME!" done
This script will print out "Hello, John!", "Hello, Paul!", "Hello, Ringo!" and "Hello, George!" in order.
2. Shell variables
2.1 Shell variable definition
In the Shell, a variable is a name used to store a value, which can be a number, a character, a string, or a path to a file. Shell variables are very useful when writing scripts. They allow you to use the same values in different places and also allow you to dynamically change these values while the script is running.
2.2 Creating and using Shell variables
In the shell, you create a variable by assigning a value to a sequence of characters without spaces. For example, the following command creates a VAR
variable named and assigns a value to it Hello World
:
VAR="Hello World"
To use this variable, you need to precede the variable name with a dollar sign ($). For example, the following command will print Hello World
:
echo $VAR
2.3 Types of Shell variables
In the Shell, there are three main types of variables:
-
Local variables: Local variables are valid within the shell script where they are defined. If a local variable is defined in a script, the variable can only be used within the script.
-
Environment variables: Environment variables are valid for the entire system environment. If you define an environment variable in a shell script, then this variable can be used in any other shell script.
-
Positional argument variables: These variables are arguments passed to the script on the command line. They are named $1, $2, $3, etc., $1 is the first parameter, $2 is the second parameter, and so on.
2.4 Special Shell variables (for example: $?, $$)
Shell also provides some special variables, which have specific meanings in all Shell scripts:
-
$?
: This variable saves the exit status of the last executed command. If the command is executed successfully, the value of this variable is 0. Otherwise, the value of this variable is non-zero. -
$$
: This variable saves the process ID of the current shell script.
2.5 Example: Usage examples of Shell variables
Here is an example using Shell variables:
#!/bin/bash
NAME="John Doe"
echo "Hello, $NAME!"
AGE=25
echo "$NAME is $AGE years old."
INPUT=$1
echo "The input argument is $INPUT."
echo "This script's PID is $$."
echo "The exit status of the last command was $?."
This script first defines two local variables NAME
and AGE
then uses them. After that, the script uses positional argument variables $1
, and finally, the script prints out its own process ID and the exit status of the last command executed.
3. Interaction between variables and scripts
3.1 Using variables in scripts
In Shell scripts, variables are an important part of programming. Variables allow you to store and manipulate data, making your scripts more flexible and dynamic.
The basic way to use variables in a script is to put the variable inside a command or statement, just like you would on the command line. For example:
#!/bin/bash
GREETING="Hello, World!"
echo $GREETING
In this example, we first create a variable GREETING
and then use echo
the command to print its value. You can also use variables directly in strings, as in the following example:
#!/bin/bash
NAME="John"
echo "Hello, $NAME"
This script will print "Hello, John".
Another example is using variables to process multiple files in a loop:
#!/bin/bash
for FILE in *.txt
do
mv "$FILE" "${FILE%.txt}.bak"
done
.txt
This script will rename all files in the current directory to .bak
files.
3.2 Passing variables to the script through the command line
When running a shell script, you can pass variables to the script through the command line. These variables are called positional parameter variables, which are $1, $2, $3, etc., where $1 represents the first parameter, $2 represents the second parameter, and so on.
For example, the following script will print out its first and second arguments:
#!/bin/bash
echo "The first argument is $1"
echo "The second argument is $2"
If you run ./myscript.sh Hello World
this script, it will print:
The first argument is Hello
The second argument is World
You can also use the special variable sum $@
to $*
get all parameters. They both treat all arguments as a list, but within double quotes "$@"
treat each argument as a separate string and "$*"
all arguments as a separate string.
In addition, you can also use $#
variables to get the number of parameters.
Using command line arguments makes your script more flexible and easier to use in different contexts.
4. Advanced Topics in Shell Scripts and Variables
4.1 Shell functions
Shell functions are reusable blocks of code that can be called by function name anywhere in the script. The basic syntax for defining a Shell function is as follows:
function_name () {
commands
}
For example, you could define a function that prints a greeting as follows:
greeting() {
echo "Hello, $1"
}
# 调用函数
greeting "World"
This function accepts one parameter ( $1
) and prints "Hello, $1". When you call it greeting "World"
, it prints "Hello, World".
Functions can accept and return parameters, which makes them very useful when writing complex scripts. The parameters of the function are accessed through positional variables ( $1
, etc.), and the return value is returned through the command.$2
return
4.2 Debugging of Shell Scripts
Debugging is an important part of programming, helping you find and fix errors in your code. In shell scripts, you can use some built-in options and commands to aid debugging.
You can use options when executing a script -x
, which will print out each command line in the script and its results, eg bash -x myscript.sh
.
Inside the script, you can turn debugging on and off using set -x
and . set +x
When debugging is turned on, the shell prints out all executed commands and their results.
Additionally, set -e
options allow the script to exit immediately upon encountering an error, which prevents errors from accumulating and propagating.
4.3 Shell’s subshells and variable scopes
In the Shell, when you execute a script or command, it is usually executed in a new Shell instance, which is called a subshell. The child shell inherits the environment of the parent shell, but any changes made in the child shell (such as changing variables) will not affect the parent shell.
This has to do with the scope of the variable. In a shell script, the scope of a variable is limited to the shell instance in which it is defined. This means that if you define a variable in a shell script (or subshell), then the variable is only visible in that script (or subshell).
However, you can use export
the command to create an environment variable that can be used in a subshell. For example:
#!/bin/bash
export VAR="Hello, World!"
bash -c 'echo $VAR'
In this example, we first export an environment variable and then print its value in VAR
a subshell ( ). bash -c
Because VAR
it is an environment variable, it is visible in the subshell.
Remembering these scoping rules is very important when writing and understanding shell scripts.