Shell programming | Basic syntax: variables, I/O, arithmetic operations, conditional judgments, process control, functions


variable

Environment variable

Environment variables are used to initialize the startup environment of the shell and are system-defined variables.

There are several commonly used environment variables.
Insert picture description here
You can use the env command to view all environment variables, or you can directly echo to view the value of an environment variable

Location variable

We can use the shift command to move the parameters to the left, the syntax is as follows

shift 表示移动的位数 

Move left one place at a time

#!/bin/bash

echo $@
shift 1
echo $@
shift 1
echo $@
shift 1
echo $@

Insert picture description here

Special variable

$n: indicates the nth parameter of the input. When it exceeds ten, it needs to be enclosed in braces, such as ${10}
$#: Get the number of input parameters
$?: Get the execution status of the previous command, if it is 0 means successful execution, 1 means execution failed. Of course, it can also be used to get the function return value
$$: Get the pid of the current process.
$@: represents all the parameters in the current command line, but it treats each parameter differently.
$*: represents all the parameters in the current command line. But it will treat all parameters as a whole

Custom variable

The way to define a variable is very simple, you only need to assign a value to it, and you don’t need to specify the type

变量名=

When you need to delete variables , you can use the unset command

unset 变量名

If you want to declare a constant , you can use the readonly keyword, but it should be noted that the constant cannot be unset

readonly 变量名

We can also upgrade local variables to environment variables through the export command

export 变量名

Precautions

  • There can be no spaces on both sides of the equal sign
  • If there are spaces in the variable name, it needs to be enclosed in single or double quotes, otherwise it will be treated as a command
  • Variables in bash will be regarded as string types by default, and cannot directly perform arithmetic operations

Array

Define array

数组名=( 元素1 元素2 元素3 ...... )
# 元素前后以空格为间隔

Show all elements of the array

echo ${数组名[@]}

Display the number of elements in the array

echo ${#数组名[@]}

Display the i-th element of the array

echo ${数组名[i]}

For example,
use parameters as array elements to view the contents of the array

#!/bin/bash

arr=( $@ )

echo ${arr[@]}
echo ${#arr[@]}
echo ${arr[5]}

Insert picture description here


I / O

printf / echo

There are two types of output commands in the shell: printf and echo. Printf is imitated from the C language, so it can specify attributes such as type and method.

echo 输出
printf 输出

At the same time, echo will have its own line break when outputting, while printf needs to be manually added by yourself\n

read

read is used to get input from the terminal. The
syntax is as follows

read (选项)(参数)
-p:指定读取值时的提示符;
-t:指定读取值时等待的时间(秒)。

Example: get a value from the terminal and output

#!/bin/bash

read -p "请输入参数:" str
echo $str

Insert picture description here


Arithmetic operation

There are two arithmetic operation commands in the shell, let and expr

let

The syntax of let is as follows

let 变量名=let 变量名=变量名+值

It should be noted that when a variable is added to the operation, there is no need to add $ in front of the variable.
Usually for simplicity, we will also use two parentheses let

((算术式))	# 不需要空格

We usually obtain the calculation results in the following two ways

$((运算式)) 或 $[运算式]

expr

expr is used to calculate expressions, there must be spaces between each operator, and when a variable is added, $

expr  + , - , \*,  /,  %   

Conditional judgment

test

In the shell, we usually use test to make conditional judgments, return 0 when the result is true, and return 1 when it fails

The syntax is as follows:

test 判断内容

But we usually abbreviate in the form of square brackets, as follows

[ 判断条件 ] # 需要注意的是条件前后需要有空格

Commonly used judgment conditions

  1. Empty

-n: non-empty (nonzero)
-z: empty (zero)

  1. Comparison between strings

=: Strings are the same !=: Strings are different

  1. Comparison between integers

-eq: equal to (equal) -ne: not equal to (Not equal)
-lt: less than (less than) -le: less than or equal to (less equal)
-gt: greater than (greater than) -ge: greater than or equal to (greater equal)

  1. Determine file permissions

-r: have the permission to read (read)
-w: have the permission to write (write)
-x: have the permission to execute (execute)

  1. Determine file type

-f: The file exists and is a regular file (file)
-e: The file exists (existence)
-d: The file exists and is a directory (directory)


Process control

if

if is used to make logical judgments , the syntax format is as follows

if test 条件 # 或者使用[ 条件 ]
	then 
	# 执行的命令
elif test 条件	# 进行其他的分支判断
	then 
	# 执行的命令
else	# 剩余的情况
	# 执行的命令
fi

For example, determine whether the entered number is greater than ten

#!/bin/bash

a=$1

if [ $a -lt 10 ]
    then 
    echo "less than 10"
elif [ $a -gt 10 ]
    then 
    echo "greater than 10"
else
    echo "equal than 10"
fi

Insert picture description here


case

case is used for branch selection , the syntax format is as follows

case $变量名 in
    "值A")
    # 执行分支A
    ;;
    "值B")
    # 执行分支B
    ;;
    "值C")
    # 执行执行分支C
    ;;
    *)
    # 如果不为以上值,则执行缺省分支
    ;;
esac

Precautions

  • The case line must end with in, and each value must be enclosed in double quotes and end with a closing parenthesis
  • ;; represents the end of the branch, similar to break in C
  • *) represents the default mode, similar to default in C

For example the following use case

#!/bin/bash

a=$1
case $a in
    "1")
    echo "11111111111"
    ;;
    "2")
    echo "22222222222"
    ;;
    "3")
    echo "33333333333"
    ;;
    *)
    echo "default"
    ;;
esac

Insert picture description here


The loop control in the shell mainly includes for, while, until

for

The for loop in the shell has two syntaxes, one is our traditional C language for, and the other is similar to the range for in C++

# 语法1
for ((初始值; 循环条件; 变量变化))
    do
        # 执行命令
    done

# 语法2
for 变量 in 数组或者区间
    do
        # 执行命令
    done

Demonstrate separately

Calculate the cumulative sum from 1 to 100

#!/bin/bash

i=0
sum=0
for ((i=0; i<=100; i++))
    do
        sum=$[$sum+$i]
    done

echo $sum

Insert picture description here
Calculate the sum of input parameters

#!/bin/bash

sum=0
for i in $@
    do
        sum=$[$sum+$i]
    done

echo $sum

Insert picture description here


while

The logic of while is to execute the loop when the judgment condition is true

The syntax is as follows

#!/bin/bash

while [ 判断条件为真则执行 ]
    do
    # 执行命令
    done

until

until is the opposite of while, if the judgment condition is false, then until continues to execute

The syntax is as follows

#!/bin/bash

until [ 判断条件为假则执行 ]
    do
    # 执行命令
    done

function

System function

The self-built function library of the system is in the path /etc/init.d/functions . The
commonly used ones are basename and dirname , which are used to parse the path of files.

basename is usually used to get the file name , it will find the position of the last / and delete all the characters in front

basename 文件路径 [可选: 删除的字符]

E.g
Insert picture description here

dirname is mainly used to obtain the path name , it will remove the file name, and then return the remaining part

dirname 文件路径

Insert picture description here

Custom function

Custom functions are also allowed in the shell, the syntax is as follows

function 函数名() #括号中不能填任何东西
{
    
    
	# 执行命令
	# 返回值
}

Precautions

  • Brackets can not fill in any parameters passed by reference can direct $ variable name in the form of transfer, return values can use the special variable $? Obtain. If no return value is declared, the result of the last command of the function is used as the return value
  • Shell scripts are run line by line, so functions must be declared before they can be called

Get the result of adding two numbers

function add()
{
    
    
    echo $[$1+$2]
}

read -p "请输入参数A: " a
read -p "请输入参数B: " b

add $a $b

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_35423154/article/details/109278179