Shell script basics start from scratch -- the first shell script

1, Foreword

After the basic study of the previous three sections, we are finally going to enter the door of the shell. As a back-end developer, you don't have to be proficient in shell script development, but you need to master some shell programming skills. After all, shell script, as a lightweight scripting language, can help us complete some repetitive work and greatly release the labor force.

2, Understanding shell scripts

What the shell script contains

A complete shell script mainly includes the following parts

  • Run environment (specify parser), that is, the first line of shell script is usually #! / bin/bash.
  • The comments of the script indicate that there may be multiple lines of comments. Except the first line, other comments beginning with # are comments. A good shell script is easy for people to read, so comments are an essential part, especially for complex scripts.
  • Script specific commands.

How shell scripts are executed

There are two ways to execute shell scripts:

  • The bash interpreter is used to syntax the bash target shell script file. Its feature is that it is not necessary to specify the parser in the first line and set the execution permission for the script.
  • Add a. Before the script path, For example, if the script file is in the current directory, it can be used/ The script file name is used to execute the script. The feature is that the parser needs to be specified in the first line (in most cases, there will be no error if it is not written, because the system will have a default interpreter, but as a good programming habit, it is recommended to execute the interpreter in the first line). The execution permission needs to be set for the script. The second method is usually used in work.

First shell script

After all this, let's write a shell script.
Requirement: record the current time and the details of all files and their subdirectories in the current directory to / usr / local / shell / filelog txt.

fileDetails.sh

#!/bin/bash

# Record the current time and the details of all files and their subdirectories in the current directory, and add them to ` / usr / local / shell / filelog txt`

date >> /usr/local/shell/fileLog.txt
# -h display in a way convenient for human reading - R recursive display
ls -lhR ./ >> /usr/local/shell/fileLog.txt

A simple shell script is completed, and there are only two main commands.
To execute the script, we can use bash filedetails SH, but we are usually used to the second method. At this time, we need to authorize the execution permission of the script file.
You can ls first view the filedetails without execution permission SH is white. At this time, we are authorized to execute CHMOD U + X filedetails sh. Check ls again and find filedetails SH has been displayed in green, indicating that you now have execution permission on the file.
At this time, it can be used/ fileDetails.sh to execute the script.
After execution, use cat filelog Txt we found that the results of two executions were recorded. So far, a simple script is completed!

3, Types of shell script variables

shell script variables are mainly divided into three categories: user-defined variables, system predefined variables and location variables (also known as part of system predefined variables).

User defined variable

That is, user-defined variables

Define variables

Basic syntax: variable name = variable value
Variable names begin with an English letter underscore and are case sensitive.
for example

name=zhangsan
Score=100
age=18

Use variables

Syntax $variable name

echo $name
echo $Score
echo $age

If the variable name is followed by a character, you need to use ${variable name} to access the variable.

#!/bin/bash
# Definition and use of variables

name=Zhang San
age=19

echo "I am $name,I'm $age years old. "

# The variable age cannot be read correctly
echo "I am $namefeng"

# The variable age can be read correctly
echo "I am ${name}feng"

Read the keyboard input value and assign it to the variable

#!/bin/bash
# Read keyboard input

read -p "please input your name:" name
echo "Hello everyone, i'm ${name}"

The difference between ", ', and backquotes

"If there are variables in a sentence, you need to use double quotation marks.
'but Yinghao will not replace the value of the variable
The back quotation mark is located under the esc key in the upper left corner of the keyboard. Its function is to parse the command and return the result.

#!/bin/bash
# Read keyboard input

read -p "please input your name:" name
echo "Hello every, i'm ${name}"
echo "Hello every, i'm ${name}"
num=`ls | wc -l`
echo "here has ${num} files!"

Delete variable

Syntax unset variable name

unset name
unset age

System predefined variables

The common predefined variables in linux system include the following four, namely $?, $*, $#$ 0
$# gets the number of parameters in the command line.
$0 returns the name of the current process / program.
$* returns the parameters on the command line.
$0 returns the execution status of the previous command. If it is 0, it means normal. If it is not 0, it means abnormal or error

Look at an example

var.sh

#!/bin/bash
# System predefined variables

echo "The number of command line parameters read is: $#"
echo "The read parameters are: $*"

total=0
for i in $*;do
    total=$(($total+$i))
done

echo "The sum of the parameters read is $total"

ls -l | grep -P '^\d{4}-\d{2}-\d{2}$'

if [[ $?==0 ]];then
    echo "The last command was executed successfully, and the program continues to execute"
else
    echo "The execution of the previous command failed and the program terminated."
fi

Execution/ var.sh 1 2 3 4, observation results. I believe that through the above example, we have understood the predefined variables of the system.

Position variable

Relatively speaking, the location variable is relatively simple. Get the 1st to 9th variables on the command line through $1 - $9. Look directly at the example
var.sh

#!/bin/bash
# Position variable
echo "The first variable read is: $1"
echo "The second variable read is: $2"
echo "The third variable read is: $3"
sum=`expr $1 + $2 + $3`
echo "The sum of the three variables read is: $sum"
echo "The sum of the three variables read is: $(($1 + $2 +$3))"

Execute the command/ var.sh 1 2 3, the results are as follows

The first variable read is: 1
The second variable read is: 2
The third variable read is: 3
The sum of the three variables read is: 6
The sum of the three variables read is: 6

That's all about the basics of shell script today. Go and practice your skills. Guys, fight another day!!

Keywords: Linux shell bash

Added by Daniel.Conaghan1 on Thu, 16 Dec 2021 01:23:17 +0200