“This is the 11th day of my participation in the Gwen Challenge in November. See details: The Last Gwen Challenge in 2021”

1. Shell basics

Commands coexist with logical languages, similar to C

&& | | with logic, && was defeated before a command, not behind, | | is the previous command fails, behind if you can perform the command.

; Command execution is not affected

`mkdir  /home/1/2/3 &&echo "OK"`Neither command will be executed

`mkdir -p /home/1/2/3 &&echo "OK"`# displays OK because -p means that the directory will be created automatically if no directory is available, and -p means recursive creation
Copy the code

The output command

echocontentCopy the code

Echo outputs color text

Echo -e “\e[1;31m this is text.\e[0m

Echo -e “\e[1;31m \e[1;42m this is text.\e[0m” echo -e “\e[1;31m \e[1;42m this is text

Command followed by &

The & is used to put the task in the background

command &>/dev/null

Mix redirect to bottomless pit

The wildcard

  • * matches any number of characters. For example:ls aa * rm -rf *;
  • ? Matches any single characterTouch Love Loove live L7ve; ll l? ve
  • [] matches the parenthesesAny onecharacter[abc].[^a-Z]^ Represents inverse, regular expression content, except parentheses
  • () executes in a subshell(CD/boot; Ls) (umask 077; touch file1000)
  • {} collection touch file{1… 9} create file file1-file9,Mkdir /home/{111,222}, mkdir -pv /home/{3333 /{aaa, BBB}, 444}

2, variables,

Shell variables use a specific string to represent the content of the variable, and $variable refers to the value of the variable

#! /bin/bash ip=127.0. 01.Ping -c1 $IP &>/dev/null && echo"$ip is up " ||echo "$ip is down";
Copy the code

Custom variable

  • Defining variables: Variable name = variable value Variable names must start with a letter or underscore (_) and be case sensitive. Such as: IP = 127.0.0.1

  • Reference variable: $variable name or ${variable name}

  • Echo $set (all variables: including custom variables and environment variables)

  • Cancel variable: unset variable name

  • Scope: Valid only for the current shell

#! /bin/bashPing -c1 $IP &>/dev/null if [$? -eq 0]; ping -c1 $IP if [$? -eq 0]; Echo "IP is up" else echo" IP is down" fiCopy the code

The environment variable

  • Define environment variables:

    • Method one:export back_dir2=/home/backup
    • Method 2: export back_dir1Convert custom variables to environment variables
  • Reference environment variables: $variable name or ${variable name}

  • Check the environment variables: echo $variable names, env, such as env | grep back_dir2

    • Env displays all environment variables
  • Unset environment variable: unset variable name

  • Scope: valid for the current shell and subshells

  • One script uses a variable from another script:

    • Method one: Set another script variable to a global variable
    • Method 2: Load a script inside another script
#! /bin/bashEcho -e "$v1" echo -e "$v1"Copy the code

Location variables

1.sh 1 2 3 4 5 6#$1 $2 $3 $4 ${5
Copy the code

Predefined variable

expression meaning
$0 Script name
$* All parameters, which refer to the parameters that follow when the script is run
$@ All the parameters
$# Number of parameters
$$ PID of the current process
$! PID of the last background process
$? The return value of the previous command, 0, indicates success
#! /bin/bash
#If the script has no parametersif [ $# -eq 0 ]; Then echo -e "usage: 'basename $0' file" exit fi if [! -f $1]; Then# check if $1 is a regular file! Echo "error file" exit fi for IP in 'cat $1' do ping -c1 $IP &>/dev/null if [$? -eq 0]; Echo "$IP is up" else echo "$IP is down" fi doneCopy the code

Basename Basic file name dirname Basic directory name

According to the assignment

Variable name = variable value

IP =127.0.0.1 school= "HDU_University" today1= 'date +%F' today2=$(date +%F)Copy the code

Read Reads a variable value from the keyboard

  • Read the variable name

  • Read -p Information: Indicates the variable name

  • Read -t 5 -p Info: Variable name // Wait 5s

  • Read-n k Variable name // Requires K characters

The difference between ‘, ‘and’

  • “” a weak reference

  • ‘strong reference

Example:

name=”mary” ; boy1=” nameisgood”; Boy2 = ‘name is good “; boy2=’nameisgood”; Boy2 = ‘name is good’ boy1= Mary is good,boy2=$name is good;

Touch ‘date +%F’ _file_txt ‘ ‘indicates executing the inside command and executing the outside command

Variable operation

Variable operation method 1 — expr

  • expr 1+2

  • expr $v1+$v2

  • expr $v1*$v2

Variable method 2 — $(())

  • echo
    ( ( ((
    v1+$v2))

  • echo $((v1+v2))

  • echo $((5-3))

  • echo $(((5-3)*2))

  • Echo $((5**3)) // n**k

  • sum=$((1+2))

$$[] = $$[]

Same thing as method two

Variable operation method 4 let

  • let sum=2+3;

  • let i++

#! /bin/bash-c1 $IP &>/dev/null if [$? -eq 0]; /dev/null if [$? -eq 0]; then echo "$ip is up" fi let i++ doneCopy the code

Integer arithmetic

  • Echo “2 * 4” | BC

  • Echo “2 ^ 4” | BC

  • Echo “scale = n; 6/4 “| BC / / n bit decimal places

BC stands for calculation

Delete and replace variable content

Delete part of variable (itself unchanged)

Before the delete

name=www.baidu.com

  • Echo ${name#*.} delete WWW.

  • Echo ${name##*.} delete www.baidu.// greedy match delete to last one. before

After deleting

  • Echo ${name%.*} delete.com

  • Echo ${name%%.*} delete. Baidu.com/greedy Delete to last. before

slice

  • Echo ${name:0:5}// Start with position 0

  • Echo ${name:5:5}// start with position 5

  • Echo ${name:5

replace

  • Echo ${name}

  • Echo ${name/b/ b}// Change the first character b to b

  • Echo ${name//w/ w}// change w to w

3. Conditional testing

Test -d $v1 check whether v1 is a directory, bash-vx. sh is executed in debug mode,test is the same as []

You can run the man test command to view the following information

  • Test conditional expression

  • [conditional expression], [A conditional B] cannot ignore Spaces, C style can

  • [[conditional expression]]

File test

format meaning
-r file Whether the current user has the read permission
-L file Whether the file is a connection file
-b file Whether the file is a device file
-c file Whether the file is a character device file
-d file The file exists and is a directory
-e file File already exists
-f file Files exist and are regular files
-g file The file already exists and is set to the group ID
-G file The file exists and is owned by a valid group ID
-h file File exists and is symbolic link (same as -l)
-k file The file exists and has its sticky bit set
-L file File exists and is symbolic link (same as -h)
-O file The file exists and is owned by a valid user ID
-p file The file exists and is a named pipe
-r file The file already exists and has been granted read permission
-s file The file exists and the size is greater than zero
-S file The file exists and is a socket
-u file The file exists and its Settings user ID bit is set
-w file The file already exists and is granted write permission
-x file The file exists and is granted execute (or search) permission

The numerical test

INTEGER1 -eq INTEGER2 # is equal to the
		  INTEGER1 is equal to INTEGER2

INTEGER1 -ge INTEGER2# greater than or equal to
          INTEGER1 is greater than or equal to INTEGER2

INTEGER1 -gt INTEGER2# is greater than the
          INTEGER1 is greater than INTEGER2

INTEGER1 -le INTEGER2Less than or equal to
          INTEGER1 is less than or equal to INTEGER2

INTEGER1 -lt INTEGER2# is less than
          INTEGER1 is less than INTEGER2

INTEGER1 -ne INTEGER2# is not equal to
          INTEGER1 is not equal to INTEGER2
Copy the code

C-style numerical judgment

(C condition judgment)

#! /bin/bash
# if the script has no arguments
if [ $# -eq 0 ]; then
	echo -e "usage: `basename $0` file" Execute the command inside the quotation marks
	exit
fi
if [ ! -f The $1 ]; then
	echo "error file"
	exit
fi

for ip in `cat The $1`
do
	ping -c1 $ip &>/dev/null
	if(($? = = 0));then #if followed by a space
		echo "$ip is up"
	else
		echo "$ip is down"
	fi
done
Copy the code

String comparison

 -n STRING# The string is not empty
 	the length of STRING is nonzero

STRING equivalent to -n STRING

-z STRING# The string is empty
	the length of STRING is zero

STRING1 = STRING2# is equalthe strings are equal STRING1 ! = STRING2# are not equal
	the strings are not equal
Copy the code

expression

( EXPRESSION )
              EXPRESSION is true

! EXPRESSION
              EXPRESSION is false

EXPRESSION1 -a EXPRESSION2
              both EXPRESSION1 and EXPRESSION2 are true

EXPRESSION1 -o EXPRESSION2
              either EXPRESSION1 or EXPRESSION2 is true

Copy the code

The user to create

#! /bin/bash
read -p "Please input the number of users: " number
if[[!"$number"= ~ ^ [0-9] + $]];then
	echo "$number is not number."
fi
read -p "Please input a name for users: " string

for i in `seq $number`
do
	user=$string$number
	useradd $user 
	if [ $? -eq 0 ];then
		echo "$user is created."
	fi
done
Copy the code

4. Flow control and circulation

if

ifConditions for testingthencontentelifConditions for testingthencontentelifConditions for testingthencontentelse # notice that there is no then plus then error syntaxcontentfi
Copy the code

case

"> < span style =" max-width: 100%; clear: both; # semicolons must not be less than pattern 2) command sequence; Mode 3) Command sequence; *) No matching default sequence ESACCopy the code

Example: Delete a user

#! /bin/bash
#del user
#by dengwei
#The date 2021.4.21read -p "Please input a user: " user id $user&>/dev/null if [ $? -ne 0 ]; then echo "username is not exist" exit -1 fi read -p "Are sure? [y]" action case "$action" in y|Y|yes|YES) userdel -r $user echo "success" ;; "*") echo "exit" esacCopy the code

A simple test

#! /bin/bash#del user
#by dengwei
# date 2021.4.21

read -p "Please input a user: " user


read -p "Are sure? [y]" action
case "$action" in
y|Y|yes|YES)
        echo "success"
        ;;
"*")
        echo "exit"
esac
Copy the code

For (while is best for line by line processing)

forvariablein{Value list}doCommand sequencedone

forvariableGet all parameters without adding anything after #
doCommand sequencedone
Copy the code

Example:

#! /bin/baship=www.baidu.com for i in {1.. {} &ping -c1 $IP &>/dev/null if [$? -eq 0]; then echo "$ip" fi }& donewait#Wait until all background endsEcho "Finish" {}& # Put the loop in the background to speed things up {}&Copy the code

IFS= “\n” Split IFS by line modify delimiter

#! /bin/bash
IFS="\n"
if [ $# -eq 0 ];then
        echo "please input a file"
        exit- 1fi

if  [ ! -f The $1 ];then
        echo "The $1 isn't a file"
        exit- 1fi

for i in `cat The $1`
do
                echo "$i"
done
Copy the code

while

The while condition tests the body of the DO loopdone#<file/The $1Input redirection later
Copy the code

A conditional test is executed when true

until

Until the condition tests the do loop body doneCopy the code

A conditional test is executed when false

Break (same as C)

Continue (same as C)

Exit (same as C)

shift

Shift n shifts the position variable to the left, shift n to the left, and reduces the total number of arguments

Sh 1 2 3 Internal scriptshift1 Once, the parameters change to 2 and 3 respectivelyThe $1 $2
Copy the code

5. Arrays and functions

array

Normal array definition:

Array name =(v1 v2 v3 v4 v5 v6)#Index 0, 1, 2, 3, 4, 5Array name =(v1 v2 v3 v4 v5 [20]=v6)#Index 0, 1, 2, 3, 4, 20Array name [0]=v1 array name [1]=v2 array name [2]=v3 array name [3]= V4Copy the code

Associative arrays are defined like hash tables

Name =([name]=jack [age]=18)#The index name age
Copy the code

function

Two comments must be noted

Function name () {# internal position arguments are the arguments of the function call function block} function name parameter # this position argument is the arguments of the script call function {function block} function name parameterCopy the code
#! /bin/bashFactorial() {val=1 for I in 'seq $1' # Do val=$(($val*$I)) done echo "$val"} result= 'Factorial $1' #sh echo "Factorial"Copy the code

Seq 8 is 1, 2, 3, 4, 5, 6, 7, 8

#! /bin/bash

test(a){
    return  $[2* $1]
}

test $1
res=$?
echo "$res"
Copy the code

A return is the return value of a program or function after it has run. Echo is the desired result of a function after it has run. This result can be stored by assigning to another variable and used as a return value

Store the return value into an array

Returns an array of

#! /bin/bashNum =(4 5 6) array() {array() {array() {array() {array() {array() {array() {array() {array() {array(); Do val[j++]=$I done echo "${val[*]}"}#array ${num[*]} 
#echoYou can print B, you can't print C because C is localResult = 'array ${num[*]}' #nums#echoB cannot be printed because the above process is performed in the subshell
echo "$result"
Copy the code

It is best to have Spaces between comments and code to avoid errors