Linux shell programming basic usage and syntax notes

1. Script format requirements

Start with the following command

#!/bin/bash

2. Common execution methods of scripts

1) Grant the script permission to execute the script
Insert picture description here

2) Execute the script directly through sh
Insert picture description here

3. Shell variables

1) The variables in LinuxShell are divided into system variables and user-defined variables .

①System variables such as $HOME, $PWD, $SHELL, $USER

②User variables

用户变量的定义:变量名=值
撤销变量:unset 变量
声明静态变量:readonly 变量
注:静态变量不能unset

变量的定义规则
1)变量名称可以由字母、数字和下划线组成,但是不能以数字开头。
2)等号两侧不能有空格
3)变量名称一般习惯为大写

可以通过使用反引号(`)或者是($())运行其中的命令将结果返回
#!/bin/bash
#系统变量
echo "PATH=$PATH"
#用户自定义变量
NAME="zhangsan"
echo "NAME=$NAME"
unset NAME
echo "NAME=$NAME"
#静态变量定义
readonly AGE=11
echo "AGE=$AGE"
unset AGE

Run
Insert picture description here
result` and $

#!/bin/bash
#反引号和$
echo `-ls`
echo ""
echo $(-ls -l)

operation result
Insert picture description here

4. Set environment variables

1) Basic grammar

①export variable name=variable value (function description: export shell variables as environment variables)

②source configuration file (function description: let the modified configuration information take effect immediately)

③echo $ variable name (function description: query the value of environment variable)
2) Step ①Finally
define the following content in the /etc/profile file

#添加环境变量
export YEAR=2021

②View the configured environment variables

#打印添加的环境变量
echo $YEAR
#使配置生效
source /etc/profile
echo $YEAR

Note: Before outputting environment variables, you need to make them take effect using the following commands

source /etc/profile

running result
Insert picture description here

5. Positional parameter variables

parameter Features
$n n is a number, $0 represents the command itself, $1-$9 represents the first to ninth parameters, parameters above ten, parameters above ten need to be enclosed in braces, such as ${10}
$* This variable represents all the parameters in the command line, $* regards all the parameters as a whole
$@ This variable also represents all the parameters in the command line, but $@ treats each parameter differently
$# This variable represents the number of all parameters in the command line
#!/bin/bash
#$n
echo "---$0---$1---$2---"
#$* 
echo "$*"        
#$@         
echo "---$0---$1---$2---"
#$# 
echo "参数个数:$#"

running result
Insert picture description here

6. Predefined variables

parameter Features
$$ Process ID (PID) of the current process
$! Process ID (PID) of the last process running in the background
$? The return status of the last executed command. If the value of this variable is 0, it proves that the previous command was executed correctly; if the value of this variable is not 0 (which number is determined by the command itself), it proves that the previous command was executed incorrectly.
#!/bin/bash
#$$
echo "当前进程号:$$"
./vim &
#$!
echo "最后的进程号:$!"
#$?
echo "执行的值:$?"

operation result
Insert picture description here

7. Operator

1) "$((Expression))" or "$[Expression]"
2) expr m + n Note that there must be spaces between expr operators

#!/bin/bash
#$((运算式))或$[]
echo "$((1+3))"
echo "$[1+4]"
#expr
echo `expr 1 + 5`

operation result
Insert picture description here

8. Condition judgment

1) Basic grammar

[condition](注意condition前后要有空格)
#非空返回true,可使用$?验证(0为true,>1为false)

2) Commonly used judgment conditions

①Integer comparison

symbol Features
= String comparison
-lt Less than
-the Less than or equal to
-eq equal
-gt more than the
-give greater or equal to
-born not equal to

②Judge according to file permissions

symbol Features
-r Have read permission
-w Have write permission
-x Have execute permission

③Judge according to file type

symbol Features
-f The file exists and is a regular file
-e File exists
-d File exists and is a directory
#!/bin/bash
#判断相等
if [ 1 -eq 1 ]
then
        echo "相等"
fi               
#判断文件是否有执行权限
if [ -w /home/zuieyuyi/shell/hello2.sh ]
then       
        echo "可写"
fi                  
#判断文件是否存在
if [ -e /home/zuieyuyi/shell/hello.sh ]
then
        echo "存在"
fi

operation result
Insert picture description here

9. Process control

1) If judgment

if [ 条件判断式 ];then
	程序
fi

======推荐使用的方式======
if [ 条件判断式 ]
then
	程序
elif [ 条件判断式 ]
then
	程序
fi
#!/bin/bash
if [ 1 -eq 1 ]
then
        echo "相等"
fi

operation result
Insert picture description here

2) case statement

case $变量名 in
"值1")
	如果变量的值等于值1,则执行程序1;;
"值2")
	如果变量的值等于值2,则执行程序2;;
...省略其他分支...*)
	如果变量的值都不是以上的值,则执行此程序;;
esac
#!/bin/bash
case $1 in
"1")
        echo "1";;
"2")
        echo "2";;
"3")
        echo "3";;
esac

operation result
Insert picture description here

3) for loop

语法一:
for 变量 in 值1 值2 值3...
do
	程序
done
===================================
语法二:
for ((初始值;循环控制条件;变量变化))
do
	程序
done
#!/bin/bash
#打印参数
for i in $@
do
        echo "$j"
done
#打印1加到100的总和
SUM=0
for ((1=1;i<=100;i++))
do
        SUM=$[ $SUM+$i ]
done
echo "$SUM"

operation result
Insert picture description here

4) while loop

while [ 条件判断式 ]
do
	程序
done
#!/bin/bash
i=0
#打印0到n的值不包括0
while [ $i -lt $1 ]
do
        i=$[$i+1]
        echo "$i"
done

operation result
Insert picture description here

10. Read to read console input

read 选项 参数

选项:
-p:指定读取值时的提示符;
-t:指定读取值时等待的时间(秒),如果没有在指定的时间内输入,就不再等待了。
#!/bin/bash
#读取控制台输入一个num
read -p "请输入一个数:" NUM1
echo "你输入了:$NUM1"
#读取控制台输入一个num(在10秒内输入)
read -t 10 -p "请输入一个数:" NUM2
echo "你输入了:$NUM2"

operation result
Insert picture description here

11. Function

1) System function

  • basename file path file suffix function: return the last part of the full path, often used to get the file name
  • dirname file absolute path function: remove the file name (non-directory part) from the given file name containing the absolute path, and then return the remaining path (directory part)

Insert picture description here

2) Custom function

function 方法名(){
	Action;
	return int;		#可有可无
}

调用方式
方法名 参数1 参数2
#!/bin/bash
#计算和
function getSum(){
    
    
        SUM=$[$n1+$n2]
        echo "$SUM"
}
read -p "输入第一个数:" n1
read -p "输入第二个数:" n2
#调用方法
getSum $n1 $n2

operation result
Insert picture description here

Guess you like

Origin blog.csdn.net/magicproblem/article/details/112720874