[embedded introductory learning notes] - V. shell programming

Embedded introductory Learning Series notes index

1, Introduction to Linux

2, deb package management

3, Special characters in shell

4, Linux common commands

5, shell programming

catalogue

1, shell and variables

1.shell script Basics

2.shell variables

2.1 user defined variables

2.2} position variables (command line parameters)

2.3 predefined variables

2.4 environmental variables

2, shell statement

1. Common functional statements

1.1 read command

1.2 expr command

2. Test statement

test

3. Structural statements

3.1 conditional statements

3.2 multi branch statements

3.3 circular statement for

3.4 loop statement while

3.5 loop control statement

3, Functions

1.shell function call

2. Function variable scope

1, shell and variables

1.shell script Basics

Programming languages are divided into compiled languages and interpreted languages. shell scripting language is an interpreted language.

Shell scripts are essentially an ordered collection of shell commands.

The basic process of shell programming is divided into three steps:

① Establish SHELL file: a text file containing any multiple lines of operating system commands or shell commands;

② Give shell file execution permission: modify the permission with chmod command;

③ Execute the shell file: call the shell program directly on the command line

2.shell variables

The shell allows users to create variables to store data, but does not support data types (integer, character, floating point). Any value assigned to a variable is interpreted as a string of characters

count=1   #Don't add spaces before and after the equal sign here, otherwise an error will be reported
echo $count
DATE=`date`   #There is no space before and after the equal sign here
echo $DATE

Bourne Shell (suffix. sh) has the following four variables:

  • User defined variable
  • Location variable (command line parameter)
  • Predefined variables
  • environment variable

2.1 user defined variables

User defined variables are generally capitalized for easy identification

COUNT=1

Add $before the variable to call the variable

echo $HOME

Use the unset command to delete the assignment of a variable

Z=hello
echo $Z

unset Z
echo $Z

2.2 # position variables (command line parameters)

$0: contains the script file name as the command line you typed

$1,$2,.......$ 9,.....: Contains the first to tenth command line arguments, respectively

$#: number of command line parameters (excluding $0)

$@: contains all command line parameters (excluding $0)

$?: Contains the push out status of the previous command (0 indicates normal exit)

$*: contains all command line parameters (excluding $0)

$$: contains the ID number of the process being executed

2.3 predefined variables

2.4 environmental variables

Common shell environment variables

The user HOME directory listed in the HOME: / etc/passwd file

IFS: Internal Field Separator, which defaults to spaces, tab s, and line breaks

PATH: shell search PATH

PS1, PS2: default prompt ($) and line feed prompt (>)

TERM: terminal type. Commonly used are vt100, ansi, vt200, xterm, etc

2, shell statement

shell statements include three categories: 1 Illustrative statements, 2 Functional statements, 3 Structural statements.

Among them, the explanatory statement starts with the # sign and ends at the line, and is not interpreted and executed; Functional statements are arbitrary shell commands, user programs or other shell programs; Structural statements include conditional test statements, multi branch statements, loop statements, loop control statements, etc.

1. Common functional statements

Any shell command, user program, or other shell program

1.1 read command

read reads a line from the standard input and assigns it to the following variables. Its syntax is

read var
#Assign all the read data to var (separated by spaces)
read var1 var2 var3  
#If there is no data in the standard input when executing the read statement, the program stays here and waits until the data arrives or the operation is terminated

# example1  for  read
echo  "Input  your  name: \c"
read  username
echo  "Your name is  $username"
# example2  for  read
echo "Input  date  with  format  yyyy  mm dd: \c"
read  year  month  day
echo  "Today  is  $year/$month/$day,  right?"
echo  "Press  enter  to  confirm  and  continue\c"
read  answer
echo "I  know  the  date,  bye!"

1.2 expr command

It is mainly used for simple integer operations, including addition (+), subtraction (-), multiplication (\ *), division (/) and modulus (%), such as

> expr  12  +  5  \*  3  # The backslash removes the metacharacter meaning of the * sign
27
> expr  3  -  8  /  2  # Spaces should be added before and after the operation symbols
-1

> num=9
> sum=`expr  $num  \*  6`  # The apostrophe refers to the running result of the command
> echo  $sum
54

2. Test statement

test

The test statement can test three objects: ① string ② integer ③ file attribute

Each test object has several test operators, such as:

test  "$answer"  =  "yes"#  Whether the value of the variable answer is the string yes
test  $num –eq  18       # Whether the value of the variable num is an integer 18
test  -d  tmp            #Test whether tmp is a directory name

String test

s1 = s2} test whether the contents of the two strings are exactly the same

s1 != s2) test whether the contents of two strings are different

-z s1 test whether the length of s1 string is 0

-n s1 test whether the length of s1 string is not 0

Integer test

a -eq b - test whether a and b are equal

a -ne b} test whether a and b are not equal

a -gt b - test whether a is greater than b (great than)

a -ge b} test whether a is greater than or equal to b (great equal)

a -lt b - test whether a is less than b (less than)

a -le b} test whether a is less than or equal to b

File test

-d name test whether name is a directory

-e name , test whether a file exists

-f name = test whether name is a normal file

-L name = test whether name is a symbolic link

-r name = test whether the name file exists and is readable

-w name = test whether the name file exists and is writable

-x name = test whether the name file exists and is executable

-s name , test whether the name file exists and its length is not 0

Test if file f1 is newer than file f2

Test if file f1 is older than file f2

3. Structural statements

Structural statements mainly control the running process of the program according to the running state of the program, input data, value of variables, control signal, running time and other factors.

It mainly includes: conditional test statements (two branches), multi branch statements, loop statements, loop control statements and background execution statements.

3.1 conditional statements

It should be noted here that if the condition is true in the shell, the return is 0 instead of 1. For the judge [], as long as the content in the symbol is true, it is successful. Do not use 0 1 to understand it, which is easy to mix dishes.

if...then...fi

Syntax structure:

if expression

then command table

fi

  • If the expression is true (0), execute the command in the command table; Otherwise, exit the if statement, that is, execute the statement after fi.
  • if and fi are statement brackets of conditional statements and must be used in pairs;
  • The commands in the command table can be one or several.
#The statement of if... then... fi
if   [  -f   $1  ]         (Whether the test parameter is a file)
then
	echo "File  $1  exists"                     (Reference variable value)
fi
if   [  -d   $HOME/$1  ]                    (Test whether the parameter is a directory)
then 
	echo "File  $1 is  a  directory"       (Reference variable value)
fi

if...then...else...fi

Syntax structure:

if expression

then command table 1

else command table 2

fi

If the expression is true, execute the command in command table 1, and then exit the if statement; Otherwise, execute the statement in command table 2 and exit the if statement

Note: there are statements to execute whether the expression is true or not

###When the condition tested by the test command is true, the return value of the command is true (0), otherwise the return value is false (non-0)

#Mode 1
test $name -eq $1
echo $?

#Mode 2
if test -f $filename
    then
    ......
fi

#Method 3, replace the test statement with square brackets
if [ -f $filename ]     #There must be at least one space at the beginning and end of square brackets
    then
    ......
fi

3.2 multi branch statements

case......esac

Syntax structure:

case  String variable   in          #The case statement can only detect string variables

        Mode 1)                #The available file name metacharacters in each mode end with right parentheses

                Command table 1

                ;;

        Mode 2|Mode 3)           #Multiple patterns can be matched at a time, separated by "|"

                Command table 2

                ;;              #The command table ends with a separate double semicolon line, pushing out the case statement

        ......

        pattern n)                  #Mode n is often written as a character * to indicate all other modes

                Command table n

                ;;               #The last double semicolon line can be omitted

esac

example:

# The statement of  case...esac
if   [  $#  -eq  0  ]
then
		echo  "No argument is declared"
		exit
fi
case  $1  in
		file1)
			echo  "User selects file1"
			;;
		file2)
			echo  "User selects file2"
			;;
		*)
			echo  "You must select either file1 or file2!"
			;;
esac

3.3 circular statement for

Syntax format:

for variable name in word list

do

Command table

done

Variable takes each word in the word list in turn. Each time a word is taken, the command in the loop body is executed The number of cycles is determined by the number of words in the word list The commands in the command table can be one or multiple commands separated by semicolons or line breaks. Multiple lines separated by line characters.

If the word list is all positional parameters on the command line, you can omit the "in # word list" part in the for statement.

Example: copy all files in the current directory to the backup subdirectory

# The statement of for...do...done
if  [  !  -d  $HOME/backup  ]
then
	mkdir  $HOME/backup
fi
flist=`ls`           #The value of flist is the execution result of ls, that is, the file name in the current directory
for  file  in  $flist
do
	if   [  $#  =  1  ]
	then
		if   [  $1  =  $file  ]      #When there is a parameter on the command line
		then
			echo  "$file  found" ;  exit
		fi
	else                             #Without parameters on the command line
		cp  $file  $HOME/backup
		echo  "$file  copied"
	fi
done
echo   ***Backup  Completed***

3.4 loop statement while

Syntax structure:

while command expression

do

Command table

done

while statementfirst tests the value of the subsequent command or expression. If it is true, execute the command in the loop body once, and then test the value of the command or expression to execute the loop body until the command or expression exits the loop when it is false.

The exit status of the while statement is the exit status of the last command executed in the command table.

Example: generate blank files in batch according to the input

# The statement for  while
if [ $# = 2 ]
then
		loop=$2           #The number of cycles is determined according to the second parameter of the command line
else
		loop=5
fi
i=1
while  [  $i  -lt   $loop  ]
do
		> $1$i    #Establish a file name prefix specified by the first parameter, such as an empty file name starting with "file" and ending with the value of variable i 
                  #See the command CMD > file
		i=`expr  $i  +  1`
done

3.5 loop control statement

break and continue

break n: jump out of layer N loop

continue: immediately go to the next loop of the nearest loop statement

continue n: go to the next round of the nearest N-level loop statement.

Instance, check the even value in the input parameter, and print

#!/bin/bash
if  [  $#  =  0  ]
then
		echo  "Numeric  arguments  required"
		exit
fi
if  [  $#  -gt   10  ]
then
		echo  "Only  ten  arguments  allowed"
		exit
fi
for  number              #The 'in word list' is omitted, indicating that number takes all positional parameters on the command line in turn
do
		count=`expr  $number  %  2` #count value can only be 0 or 1
		if  [  $count  -eq  1  ]
		then
			continue
		else
			output="$output   $number"  #So you can output a queue
		fi
done
echo  "Even  numbers:  $output "

3, Functions

1.shell function call

Mode 1:

value_name=`function_name  [arg1 arg2 ... ]`

All the standard output of the function is passed to the variables of the main program

Mode 2:

function_name  [arg1  arg2  ...  ]

echo   $?

Gets the status returned by the function

example

check_user( )    {  #Find the logged in specified user
	  user=`who  |  grep  $1 | wc -l`
        if [ $user –eq 0 ]
        then
               return  0       #The specified user was not found
        else
               return  1       #The specified user was found
        fi
}
while  true         # MAIN, Main, main:   program  begin  here
do
		echo  "Input username: \c"
		read   uname
		check_user  $uname       # Call the function and pass the parameter uname
		if [ $? –eq  1 ]                 # $? Returns a value for a function
		then	echo  "user  $uname  online"
		else	echo  "user  $uname  offline"
		fi
done

2. Function variable scope

Global scope: the variable can be accessed anywhere else in the script.

Local scope: can only be accessed within the scope of the declared variable.

Format for declaring local variables:

                Local variable_name = value

example

Scope()
{
Local lclvariable =1
Gblvariable = 2
echo "lclavariable in function = $ lclvariable "
echo "Gblvariable in function = $ Gblvariable "
}

Scope

echo "lclavariable in function = $ lclvariable "
echo "Gblvariable in function = $ Gblvariable "

Keywords: Linux shell Embedded system

Added by kovudalion on Sun, 23 Jan 2022 11:58:46 +0200