shell script tutorial

shell programming

shell overview

The parsers provided by Linux are

[root@pihao01 ~]# cat /etc/shells
/bin/sh
/bin/bash
/usr/bin/sh
/usr/bin/bash
[root@pihao01 ~]#

Relationship between bash and sh

[root@pihao01 bin]# ll |grep bash
-rwxr-xr-x. 1 root root      1219248 Nov  9  2019 bash
lrwxrwxrwx. 1 root root            4 Nov  9  2019 sh -> bash
[root@pihao01 bin]# sh is bash

The default parser for Centos is bash

[root@pihao01 bin]# echo $SHELL
/bin/bash
[root@pihao01 bin]# 

Getting started with shell Scripting

#!/bin/bash
echo "hello world !!!"

-------- implement
./helloworld.sh

variable

System predefined variables

$HOME,$PWD,$SHELL,$USER,$PATH wait

Custom variable

Basic grammar

(1)Defining variables: Variables=value    (No spaces allowed)
(2)Undo variable: unset variable
(3)Declare static variables (constants): readonly Variable, note: cannot unset

Variable name definition rules

(1)Variable names can be composed of letters, numbers and underscores, but they cannot start with numbers. Environment variable names are recommended to be capitalized.
(2)There must be no spaces on either side of the equal sign
(3)stay bash In, the default types of variables are string types, and numerical operations cannot be performed directly.
(4)If there are spaces in the value of the variable, it needs to be enclosed in double quotation marks or single quotation marks.

Promote variable scope

A=10
export A # Now this A can be referenced in the shell script
[root@pihao01 shells]# A=10
[root@pihao01 shells]# export A
[root@pihao01 shells]# vim helloworld.sh 
[root@pihao01 shells]# ./helloworld.sh 
hello world!!!
10
[root@pihao01 shells]# 

Special variable

Basic grammar

$n (function description: n is a number, $0 represents the script name, $1- 9 generation surface The first one reach The first nine individual ginseng number , ten with upper of ginseng number , ten with upper of ginseng number need want use large Include number package contain , as 9 represents the first to ninth parameters. Parameters above ten need to be contained in braces, such as 9 represents the first to ninth parameters. Parameters above ten need to be contained in braces, such as {10})

#!/bin/bashecho '==========$n=========='echo $0 # Get name echo $1 # Get the first parameter echo $2 # Get the second parameter

$# (function description: get the number of all input parameters, which is often used in loops. Note that it will be parsed only when it is used in double quotation marks)

echo "=========$#========="echo $#

∗ ( Merit can Trace State : this individual change amount generation surface life order that 's ok in place yes of ginseng number , *(function description: this variable represents all parameters in the command line, * (function description: this variable represents all parameters in the command line, * all parameters are regarded as a whole)

@ ( Merit can Trace State : this individual change amount also generation surface life order that 's ok in place yes of ginseng number , no too @(function description: this variable also represents all parameters in the command line, but @(function description: this variable also represents all parameters in the command line, but @ treat each parameter differently)

$? (the exit status of the last command is 0 or non-0, or the return value of the function)

operator

" ( ( transport count type ) ) " or " ((expression)) "or“ ((expression)) "or" [expression] "

[root@pihao01 shells]# clear[root@pihao01 shells]# echo $[(3+3)*3]18[root@pihao01 shells]# 

Conditional judgment

Basic grammar

(1)test condition

(2) [condition] (note that there should be a space before and after the condition)

Note: if the condition is not empty, it is true, [pihao] returns true and [] returns false.

Common judgment conditions

(1) Comparison between two integers

  • ==String comparison

  • -lt less than

  • -le less than or equal

  • -eq equals (equal)

  • -gt greater than

  • -ge is greater than or equal

  • -ne is Not equal to (Not equal)

(2) Judge according to file permissions

  • -r has read permission (read)

  • -w has write permission (write)

  • -x has execute permission (execute)

(3) Judge by file type

  • -The f file exists and is a regular file

  • -e file exists

  • -d file exists and is a directory

(4) Multi conditional judgment (support this & &, |)

  • [ 100 -gt 50 ] && [ 100 -lt 200 ]

Process control

if judgment

#! / bin / bashif [$1 - EQ 1] then echo "Beijing I'm coming" elif [$1 - EQ 2] then echo "Shanghai I'm coming" else echo "Shenzhen I'm coming" fi

case

#! / bin / bashcase $1 in "1") echo "white"; "2") echo "white"; *) echo "pihao";; ESAC

for loop

Basic grammar

for (( Initial value;Cycle control conditions;Variable change ))   do     program   done
#!/bin/bash# Find the sum of 100 sum = 0For ((I = 0; I < 100; I + +) do sum = $[$sum + $I] doneecho $sum
#!/bin/bashfor i  in $*    # Note that if the $* here is not enclosed in double quotation marks, it will separate do echo "hello -- $i"done

while Loop

#!/bin/bash# 100 sum sum = 0I = 0while [$I - Le 100] do sum = $[$sum + $I] I = $[$I + 1] doneecho $sum

Use more if,case in, for in

Read read console input

It is a bit similar to the scanner in java

Basic grammar

Read (option) (parameter)

Options:

-p: Specify the prompt when reading the value;

-t: Specifies the time (in seconds) to wait while reading the value.

parameter

Variable: Specifies the variable name of the read value

read -t 5 -p "Please wait at 5 s Enter name in:" NAME

System function

basename

Basic grammar

basename [string / pathname] [suffix]

(function description: the basename command will delete all prefixes, including the last ('/') character, and then display the string.

Options:

Suffix is the suffix. If suffix is specified, basename will remove suffix from pathname or string.

[root@pihao01 shells]# basename /hello/world.txtworld.txt[root@pihao01 shells]# basename /hello/world.txt .txtworld[root@pihao01 shells]# 

dirname

Basic grammar

dirname file absolute path (function description: remove the file name (non directory Part) from the given file name containing the absolute path, and then return the remaining path (directory Part))

[root@pihao01 shells]# dirname /hello/world.txt/hello[root@pihao01 shells]# 

Custom function

Basic grammar

#Define function[ function ] funname[()]{	Action;	[return int;] # This returned int Is by range, can only be 0~255}# Simplified writing function funname(){	Action;	return int;}#Call function funname

case

#!/bin/bash# Define a function total=0function sum(){  total=$[$1+$2];  return $total;  # yes bug,Can not consider return,Or you'll find a surplus}# Dynamic input read -t 5 -p "Please enter the first number: " N1read -t 5 -p "Please enter the second number: " N2#Call function sum $N1 $N2# The output result echo "and is: $?"

regular expression

  • ^Match start
  • $match end
  • . match any character
  • *Match one or more
  • [] indicates the range
  • \Indicates escape (with single quotation marks)
  • Come on, refuse comfort

Keywords: Linux shell

Added by KrisCons on Sat, 18 Sep 2021 02:29:16 +0300