Basic teaching of shell scripting

One, shell script related concepts

1.1 What is a shell

The shell is an application program that connects the user and the Linux kernel, translates the user's commands into the system language, transfers the operations that require autonomous counties to the kernel for execution, and outputs the execution results so that users can use the Linux kernel more conveniently and quickly.

1.2 The role of shell scripts

  • Save the commands to be executed to a text file in order
  • Give the file executable permissions
  • Can be combined with various shell control statements to complete more complex operations

1.3 Application scenarios of shell scripts

  • Repetitive operation (for loop)
  • Interactive task
  • Bulk transaction processing
  • Service running status monitoring (monitoring of disk space, memory usage, service status, whether the firewall is closed, etc., most commonly used by operation and maintenance personnel)
  • Scheduled task execution

1.4 Shell script interpreter

  • There are many types of Linux shell script interpreters, and a system can have multiple shell script interpreters
  • We can usecat /etc/shellsView the shell script interpreter installed on the system
    Insert picture description here
  • After the user logs in, the default hi shell program is generally /bin/bash
  • Bash is also the default shell script interpreter for most Linux systems.

Two, write the first script

2.1 The composition of the shell script

  • Script statement (interpreter): If the first line is "#!/bin/bash", it means that the code statements below this line are interpreted and executed by the /bin/bash program (/bin/bash is the default interpreter, and there are others Interpreter, such as #!/usr/bin/python, #!/usr/bin/expect)
  • Comment information, the statement at the beginning of # represents the comment information, and the commented statement will not be executed when the script is run
  • Executable statements, such as the echo command, are used to output the string between ""

2.2 Writing script code

  • Use the vim text editor, one Linux command per line, written in order of execution
    Insert picture description here

  • After editing "wq", save and exit, but note that this script cannot be run at this time. You also need to give this script executable permissions:

  • chmod +x first.sh
    Insert picture description here

2.3 Execute script file

Method 1: Script file path (absolute path and relative path)Must have x permission

./first.sh

Method 2: sh script file path

sh first.sh

Method 3: Source script path (can also be executed by ".")

source first.sh
. first.sh

Guess you like

Origin blog.csdn.net/weixin_51613313/article/details/111190441