Embedded linux development - (3) shell programming

Series Article Directory



foreword

Shell is a program written in C language, which is a bridge for users to use Linux. Shell is both a command language and a programming language.

Shell refers to an application program that provides an interface through which users access the services of the operating system kernel.

Ken Thompson's sh is the first Unix shell, and Windows Explorer is a typical graphical interface shell.


提示:以下是本篇文章正文内容,下面案例可供参考

1. Shell script

Shell script (shell script) is a script program written for the shell.

The shell mentioned in the industry usually refers to shell scripts, but readers should know that shell and shell script are two different concepts.

Due to customary reasons, for the sake of brevity, the "shell programming" in this article refers to shell script programming, not to the development of the shell itself

2. How to run a shell script

chestnut

Open a text editor (you can use the vi/vim command to create a file), create a new file test.sh, the extension is sh (sh stands for shell), the extension does not affect the script execution, just know the name, if you Use php to write shell scripts, just use php as the extension.

Enter some code, the first line is usually like this:

#!/bin/bash
echo "Hello World !"

method

1. As an executable program

Save the above code as test.sh, and cd to the corresponding directory:

chmod +x ./test.sh #Enable the script to execute./test.sh
#Execute the script
Note that it must be written as ./test.sh instead of test.sh, and the same is true for running other binary programs, directly write test .sh, the linux system will search for test.sh in the PATH, but only /bin, /sbin, /usr/bin, /usr/sbin, etc. are in the PATH, and your current directory is usually not in the PATH, so If it is written as test.sh, the command will not be found. Use ./test.sh to tell the system to find it in the current directory.

2. As an interpreter parameter

This mode of operation is to run the interpreter directly, and its parameter is the file name of the shell script, such as:

/bin/sh test.sh
/bin/php test.php
The following figure is a screenshot of our operation:
insert image description here

shell script syntax

1. Variables

grammar:

  • Names can only use English letters, numbers and underscores, and the first character cannot start with a number.
  • There can be no spaces in the middle, and the underscore _ can be used.
  • Punctuation cannot be used.
  • Keywords in bash cannot be used (use the help command to view reserved keywords).

Sample code:

#!/bin/bash
yourname="666"
echo "your name is $yourname"

Running results:
insert image description here
Note : You don’t need to add "$" when defining, but you need to add "$" when quoting

2. Input and output

Grammar :

The output command echo
echo -e enables escaping, and the following characters can be escaped

\a 发出警告声; 
\b 删除前一个字符; 
\c 最后不加上换行符号; 
\f 换行但光标仍旧停留在原来的位置; 
\n 换行且光标移至行首; 
\r 光标移至行首,但不换行; 
\t 插入tab; 
\v 与\f相同; 
\ 插入\字符; 
\nnn 插入nnn(八进制)所代表的ASCII字符;

echo -n no newline output

Enter the command read
-p prompt statement, followed by the input prompt information, here is 'Enter Password: '
-n The number of parameters, sometimes to limit the length of the password, or other input length restrictions, such as [Y/N], only enter the input One, -n1
-s shields the echo, does not display the input content on the screen, generally used for password input
-t wait time, here is set to 30 seconds, no input or incomplete input within 30 seconds, terminate
-d input limit, here is , input to, input to, input to , naturally terminate the input
-r to shield the translation function of the special character \, after adding it, it will be treated as an ordinary character

Sample code:

#!/bin/bash
read -p "pleadse input your name" yourname
echo "your name is $yourname"

Running result:
insert image description here
Note: Do not add "$" in front of the read variable

3. Shell passing parameters

We can pass parameters to the script when executing the Shell script, and the format of getting the parameters in the script is: $n. n represents a number, 1 is the first parameter to execute the script, 2 is the second parameter to execute the script, and so on... In the following
example, we pass three parameters to the script and output them respectively, where $0 is the executed file name (including file path):

#!/bin/bash

echo "Shell 传递参数实例!";
echo "执行的文件名:$0";
echo "第一个参数为:$1";
echo "第二个参数为:$2";
echo "第三个参数为:$3";

Running result:
insert image description here
Special handling:
insert image description here

4. test command

The test command in the Shell is used to check whether a certain condition is true, and it can perform tests in three aspects: numerical value, character and file.

numerical test

insert image description here
Example:

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

operation result:
insert image description here

string test

insert image description here

file test

insert image description here

5. Shell process control

if else

Grammar format:

if condition
then
    command1 
    command2
    ...
    commandN 
fi

if else-if else syntax format:

if condition1
then
    command1
elif condition2 
then 
    command2
else
    commandN
fi

The […] judgment statement of if else uses -gt for greater than and -lt for less than.

if [ "$a" -gt "$b" ]; then
    ...
fi

If you use ((…)) as a judgment statement, you can directly use > and < for greater than and less than.

if (( a > b )); then
    ...
fi

Example :

#!/bin/bash
read -p "please input two int num:" first second
if [ "$first" == "$second" ]
then
    echo "$first = $second"
elif (($first > $second))
then
    echo "$first > $second"
else
    echo "$first < $second"
fi

operation result:
insert image description here

for loop

Similar to other programming languages, the shell supports for loops.
The general format of a for loop is:

for var in item1 item2 ... itemN
do
    command1
    command2
    ...
    commandN
done

Example:

for loop in 1 2 3 4 5
do
    echo "The value is: $loop"
done

Output result:

The value is: 1
The value is: 2
The value is: 3
The value is: 4
The value is: 5

Example 2:
Input an integer and output 1+2+. . . +n results

#!/bin/bash
read -p "please input int num:" num
count=0
for((i=0; i<=num; i=i+1))
do
    count=$(($count+$i))
done

echo "1+2+3+...$n = $count"

insert image description here

while statement

A while loop is used to continuously execute a sequence of commands, and is also used to read data from an input file. Its syntax format is:

while condition
do
    command
done

until loop

until Loop executes a sequence of commands until a condition is true and stops.
The until loop is the exact opposite of the while loop.
In general a while loop is better than an until loop, but sometimes—and only rarely—an until loop is more useful.
until syntax format:

until condition
do
    command
done

case … esac

case ... esac is a multi-choice statement, which is similar to switch ... case statements in other languages. It is a multi-branch selection structure. Each case branch starts with a right parenthesis, and two semicolons ;; indicate break, which means the end of execution , jump out of the entire case ... esac statement, and esac (that is, the case in reverse) is used as the end tag.
You can use a case statement to match a value and a pattern, and if the match is successful, execute the matching command.
The syntax of case ... esac is as follows:

case 值 in
模式1)
    command1
    command2
    ...
    commandN
    ;;
模式2)
    command1
    command2
    ...
    commandN
    ;;
esac

break out of the loop

break command
The break command allows breaking out of all loops (terminating execution of all subsequent loops).
In the example below, the script enters an infinite loop until the user enters a number greater than 5. To break out of this loop and return to the shell prompt, you need to use the break command.
continue
The continue command is similar to the break command, except that it does not break out of all loops, only the current loop.

6. Shell function

The linux shell can user-defined functions, and then they can be called casually in shell scripts.
The definition format of a function in the shell is as follows:

[ function ] funname [()]
{
    
    
    action;
    [return int;]
}

illustrate:

1. It can be defined with function fun(), or directly defined with fun() without any parameters.
2. Parameter return can be displayed and added: return return, if not added, the result of the last command will be used as the return value. return followed by the value n(0-255


Summarize

This article makes a brief summary of shell commands. If you are interested in shell programming, you can refer to: rookie tutorial - shell programming

Guess you like

Origin blog.csdn.net/qq_52608074/article/details/127484559