Linux embedded development - shell script

Linux embedded development - shell script

After our previous studies, we have been able to enter commands in the terminal to complete some common operations, but we input commands one by one. If there are more commands to be executed, it will be very troublesome. So is there a way to put many commands into one file, and then run this file directly to execute these commands? Of course, this is the shell script we will introduce next!

The shell script is similar to the batch file of windows, which is to write the commands executed continuously into a file. Shell scripts provide functions such as arrays, loops, and conditional judgments, which are generally mastered by Linux operation and maintenance or system administrators, but as embedded developers, we only need to master the most basic parts of shell scripts.

1. Basic principles of shell scripting

A shell script is a plain text file, and commands are executed line by line from top to bottom. Shell scripts have a .sh extension. And the first line of the shell script must be:

#!/bin/bash

This means using bash.

Two, shell script syntax

2.1, write shell script

Next, let's write the first simple shell script, the main function is to display "hello world!" on the terminal. Let's take a look at the specific code next!

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

But let's take a look at the permissions of this .sh file!

-rw-rw-r-- 1 ygr ygr 32  126 15:08 my.sh

We can see that this file is not executable, so we modify the permissions to make it executable.

chmod 777 my.sh

Next, let's execute this file and see what the final output is. We can see that our "hello world!" is output at the end.

ygr@ygr-virtual-machine:~/桌面$ ./my.sh 
hello world!

2.2. Interactive shell script

Next, what we are going to touch is the interactive script. We have already learned to print in the terminal. Next, let's learn how to input. The command we use is the read command, let's take a look at our specific code:

#!/bin/bash
echo "please input name:"
read name
echo "your name:" $name

Then run the effect:

please input name:
chenyi
your name: chenyi

Our read command can add many parameters, we will only briefly introduce one, and you can check the rest by yourself.

#!/bin/bash
read -p "please input name and age: " name age
echo "your name = $name, your age = $age."

This command is used to prompt the user when inputting. Let's take a look at the running results:

please input name and age: chenyi 30
your name = chenyi, your age = 30.

2.3, Numerical calculation of shell script

The shell only supports integers, and we use the following statements to perform numerical calculations:

#!/bin/bash
echo "please input two int num: "
read -p "first num: " first
read -p "second num: " second
total=$(($first + $second))
echo "$first + $second =  $total"

operation result:

please input two int num: 
first num: 4
second num: 6
4 + 6 =  10

2.4, test command

The test command is mainly used to check whether the file exists, permission and other information. It can test the value, character and file. Before that, let's introduce the two commands && and ||:

&& operator

We know that "&&" means and in C language, but in shell syntax, this does not mean and, but it is a bit similar. Let's take an example to see next.

"cmd1 && cmd2" means that when cmd1 is executed and correct, then cmd2 starts to execute, if cmd1 executes incorrectly, then cmd2 does not execute. It can only be said to be a bit like a short circuit in the C language. Next, let's introduce the || operator.

|| operator

We know that "||" means or in C language, but in shell grammar, this does not mean or, but rather, let's take an example to see next.

"cmd1 || cmd2" means that when cmd1 is executed and correct, cmd2 will not be executed, otherwise cmd2 will be executed. It is the implementation of one of the two, so I say yes or mean. And these two commands are generally used in combination.

Next, let's take a look at the specific usage of the test command!

#!/bin/bash
read -p "please input file name: " filename
test -e $filename && echo "$filename exist" || echo "$filename no exist"

operation result:

please input file name: C-test
C-test exist

This is to check whether the file exists, let's take a look at the judgment of the string:

#!/bin/bash
echo "please input two string: "
read -p "first string: " first
read -p "second string: " second
test $first == $second && echo "equality" || echo "inequality"

operation result:

please input two string: 
first string: qwert
second string: qwert
equality

please input two string: 
first string: qwe
second string: asd
inequality

2.5, square brackets [] judge

The [ ] judge, as the name suggests, is used to judge, but only == or != can be entered in it. Next, let's look at the specific usage method:

#!/bin/bash
echo "please input two string: "
read -p "first string: " first
read -p "second string: " second
[ "$first" == "$second" ] && echo "equality" || echo "inequality"

This command is equivalent to the one above. Note, however, that variables must be enclosed in double quotes.

2.6. Default variables

Let's introduce the default variables next, so let's look at some default variables:

  • $0 ~ $n, indicating the parameters of the shell script, including the shell script command itself, the shlle script command itself is $0

  • $#: # indicates the label of the last parameter.

  • $@: table $1, $2, $3...

Let's take a look at the specific code:

#!/bin/bash
echo "file name:" $0
echo "total parameter num: " $#
echo "all paramenters: " $@
echo "first paramenters: " $1
echo "second paramenters: " $2

operation result:

ygr@ygr-virtual-machine:~/桌面$ ./my.sh qw er rt
file name: ./my.sh
total parameter num:  3
all paramenters:  qw er rt
first paramenters:  qw
second paramenters:  er

Three, shell script condition judgment

if then

Although our shell script can achieve simple conditional judgment through && and ||, it is not suitable for slightly more complicated scenarios. So the shell script provides us with an if then conditional judgment statement, written as follows, let's take a look at the specific code usage:

if 条件判断 ; then
//判断成立要做的事情
fi
  1 #!/bin/bash
  2 
  3 read -p "please input(Y/N): " value
  4  if [ "$value" == "Y" ] || [ "$value" == "y" ]; then
  5          echo "your input is Y !"
  6          exit 0
  7  fi
  8 
  9  if [ "$value" == "N" ] || [ "$value" == "n" ]; then
 10          echo "your input is N !"
 11          exit 0
 12  fi

The running results are as follows:

ygr@ygr-virtual-machine:~/桌面$ ./my.sh
please input(Y/N): y
your input is Y !
ygr@ygr-virtual-machine:~/桌面$ ./my.sh
please input(Y/N): n
your input is N !

if then else

In addition to if then, we also have if then else statement, which is similar to if else in C language. The specific writing method is as follows:

if 条件判断 ; then
//条件判断成立要做的事情
else
//条件判断不成立要做的事情。
fi

或:

if 条件判断 ; then
//条件判断成立要做的事情
elif [条件判断]; then
//条件判断成立要做的事情
else
//条件判断不成立要做的事情。
fi

Let's take a look at the specific code:

  1 #!/bin/bash
  2 
  3 read -p "please input(Y/N): " value
  4  if [ "$value" == "Y" ] || [ "$value" == "y" ]; then
  5          echo "your input is Y !"
  6          exit 0
  7  else
  8          echo "your input is: $value !"
  9          exit 0
 10  fi

The running results are as follows:

please input(Y/N): t
your input is: t !

please input(Y/N): y
your input is Y !

Next is elif, let's take a look at the specific usage code:

  1 #!/bin/bash
  2 
  3 read -p "please input(Y/N): " value
  4 if [ "$value" == "Y" ] || [ "$value" == "y" ]; then
  5         echo "your input is Y !"
  6         exit 0
  7 elif [ "$value" == "N" ] || [ "$value" == "n" ]; then
  8         echo "your input is: $value !"
  9         exit 0
 10 else
 11         echo "your input is not recognized!"
 12 fi

operation result:

please input(Y/N): r
your input is not recognized!

please input(Y/N): y
your input is Y !

please input(Y/N): n
your input is: n !

case

Next, let's introduce the case statement, which is similar to our case in C language. The specific writing method is as follows:

case $变量 in

“第1个变量内容”)
程序段
;;   # 表示该程序块结束!!

“第2个变量内容”)
程序段
;;

“第n个变量内容”)
程序段
;;

esac

Next, let's take a look at the specific code implementation:

  1 #!/bin/bash
  2 
  3 case $1 in
  4         "chen")
  5                 echo "chen yi is my baby!"
  6                 ;;
  7         "ye")
  8                 echo "ye! happy every day!"
  9                 ;;
 10         *)
 11                 echo "your input is not recognized!"
 12                 ;;
 13 esac

The running results are as follows:

ygr@ygr-virtual-machine:~/桌面$ ./my.sh ye
ye! happy every day!

ygr@ygr-virtual-machine:~/桌面$ ./my.sh chen
chen yi is my baby!

ygr@ygr-virtual-machine:~/桌面$ ./my.sh chr
your input is not recognized!

Four, shell script function

without parameters

Shell scripts also support functions. Functions without parameters are written as follows:

function fname () {
    
    
    # 函数代码段
}

The specific code is as follows:

  1 #!/bin/bash
  2 
  3 function help(){
    
    
  4     echo "this is help cmd!"
  5 }
  6 
  7 function close(){
    
    
  8     echo "this is close cmd!"
  9 }
 10 
 11 case $1 in
 12     "-h")
 13         help
 14         ;;
 15     "-c")
 16         close
 17         ;;
 18 esac

The running results are as follows:

ygr@ygr-virtual-machine:~/桌面$ ./my.sh -h
this is help cmd!
ygr@ygr-virtual-machine:~/桌面$ ./my.sh -c
this is close cmd!

with parameters

Next, let's introduce the situation of functions with parameters. The specific writing method is as follows:

  1 #!/bin/bash
  2 
  3 print(){
    
    
  4     echo "parameter 1:$1!"
  5     echo "parameter 2:$2!"
  6 }
  7 
  8 print chen ye

The running results are as follows:

parameter 1:chen!
parameter 2:ye!

Five, the shell loop

while

Shell scripts also support loops, such as while do done, which means that when the condition is true, it will continue to loop until the condition is not true. The specific syntax format is as follows:

while [条件]  # 括号内的状态是判断式
do         # 循环开始
	# 循环代码段
done

The specific implementation code is as follows:

  1 #!/bin/bash
  2 
  3 while [ "$value" != "close" ]
  4 do
  5     read -p "please input str:" value
  6 done
  7 
  8 echo "stop while!!!"

The running results are as follows:

please input str:er
please input str:stop
please input str:close
stop while!!!

until

There is another until do done, which means looping when the condition is not true, and not looping after the condition is true. The specific syntax format is as follows:

until [条件]
do
//循环代码段
done

The specific implementation code is as follows:

  1 #!/bin/bash
  2 
  3 until [ "$value" == "close" ]
  4 do
  5     read -p "please input str:" value
  6 done
  7 
  8 echo "stop while!!!"

The running results are as follows:

please input str:co
please input str:close
stop while!!!

for

The for loop of the shell script is very similar to the for of python. In fact, it is because python is actually a scripting language. You can know the number of loops by using the for loop. The specific syntax format is as follows:

for var in con1 con2 con3……
do
# 循环代码段
done

#for循环数值处理,写法 

for((初始值; 限制值; 执行步长))
do
# 循环代码段
done

The specific syntax implementation is as follows:

  1 #!/bin/bash
  2 
  3 for name in ygr cy
  4 do
  5     echo "your name is :$name!"
  6 done

The running results are as follows:

your name is :ygr!
your name is :cy!

Next, let's look at another for loop:

  1 #!/bin/bash
  2 
  3 read -p "please input count: " count
  4 
  5 total=0
  6 for((i=0; i<=count; i=i+1))
  7 do
  8     total=$(($total+$i))
  9 done
 10 
 11 echo "前n个整数之和为: $total"

The running results are as follows:

please input count: 5
前n个整数之和为: 15

Guess you like

Origin blog.csdn.net/weixin_66578482/article/details/128946837