Linux4: shell programming (shell concept, variables, input and output, operators, expressions, conditional testing, flow control, arrays, functions)

Shell programming (the concept of shell, variables, input and output, operators, expressions, conditional testing, flow control, arrays, functions)

Application-shell command interpreter-kernel-hardware

1. The concept of shell:
Shell is an interpreted scripting language. A script is a language that does not need to be compiled and can process commands in batches.

Definition:
Interpretative scripting language, batch processing command use, similar to the .dat file under windows, an outer protection tool of the Linux kernel, responsible for the interaction between the user and the kernel.

rule:

Create a shell file:
Vim gedit touch…
The suffix of the shell file is: .sh
shell is a language with its own writing rules
Operating environment settings

 第一行 
 #!/bin/bash  //声明shell类型 bash shell
 或者
 #!/bin/sh

Script statement writing:
Shell command (if-else) + system command (ls cd cp …)
comment lines start with #

Set executable:

The shell script you create does not have execution permissions by default and needs to be set

chmod +x xx.sh

Analysis method xx.sh
Execute script file:

./xx.sh
. xx.sh
requires execution permission

2. About variables

Variables in the shell are not divided into types, they are defined directly and used directly.
When using, add: $
variable definition :

  直接定义   str=hello  //等号两端不能有空格
  双引号定义 str="hello"//保留特殊字符的含义
  单引号定义 str = 'hello' //去除特殊字符的含义
 

vim 1.sh

#!/bin/bash
str1="hello"
str=hello
echo str
echo "$str1"
echo '$str1'

chmod 777 1.sh
./1.sh

Operation result: *
Insert picture description here
Description: $: reference. Putting it in double quotation marks still serves as a quotation, and putting it in single quotation marks means removing it.

小飘号定义str=`date`  或则 str=$(date)
:用来引用系统指令
#!/bin/bash
str1="hello"
str=hello
str2=$(date)
echo "$str2"
echo str
echo "$str1"
echo '$str1'
ls
pwd

operation result:
Insert picture description here

**变量的引用**

类似于命令的重定向(命令运行结果重定向到变量内)
命令重定向
 >输出重定向(覆盖原内容)
  echo hello >1.txt
 >>输出重定向(不覆盖原内容,追加)
  echo world >>1.txt

Classification of variables

自定义变量

自己定义,自己使用

特殊变量

 $0 命令本身
 $1 $2 ....$n //取命令行参数
 $@//取所有的参数
  不包括第0个
 $?  //判断上一条命令是否执行成功,成功打印0 失败打印非0
 $#//传递参数的个数
 $$//显示当前的进程号
#!/bin/bash
echo "$0"   #显示命令本身
echo "$1"   #取命令行参数
echo "$2"   #取命令行参数
echo "$@"   #取所有参数,不包括第0个
echo "$?"   #判断上一条命令是否执行成功,成功打印0
echo "$#"   #传递参数的个数
echo "$$"   #显示当前的进程号

show result:
Insert picture description here

环境变量
 定义
  由系统维护,用于设置系统的shell工作环境,极少数用户可以修改
 示例
  执行命令的时候,就会去指定的目录(bin、sbin、usr/bin)去寻找是否有这个命令
  运行程序的时候去指定的路径(lib、usr/lib)加载库文件
 操作
  env  //显示所有环境变量
   HOSTNAME:当前主机名
   SHELL:shell类型
   QTDIR:qt安装路径
   USER:当前用户
   PATH:指定当前命令寻找路径
   ==========================================================
  设置环境变量
  
   export PATH=$PATH:/root  //将root路径添加PATH环境变量里面(重启后失效)(设置shell脚本路径)
   将这句话加入到开机自启动的文件里面即可永久生效
    /root/.bashrc
    /etc/profile(推荐)
    /etc/inittab
    /etc/rcs
  修改
   export LD_LIBRARY_PATH=./:$LD_LIBRARY_PATH(设置动态库路径,这样就不用将动态库复制到/usr/lib里了 LD_LIBRARY_PATH: 动态库的查找路径)
   
    注意
      变量都是字符串,没有类型之分,不用声明

3. Input and output
Input
read num//input num
readonly num=5 //Define read-only variable num and
output
echo command
printf

Reference Code:

#!/bin/bash
echo "qing shu ru shu:\n"
read num
echo $num
readonly n=100
echo $n

show result:
Insert picture description here
3. Operator & expression
Operators
Arithmetic operators, logical operators, assignment operators, etc.

Addition, subtraction, multiplication, division, and NOR

Four methods of calculating expressions

var = $ ((1 + 2))

var = $ [1 + 2]

let var = 1 + 2

var = $ (expr 1 + 2)

Note: Add spaces before and after the operator

4. Condition test

grammar

test conditional expression:
test expression 1 = expression 2
there must be spaces on both sides of the equal sign
test string1 = string2

[Conditional expression]
[string1 = string2]

note
If the conditional expression value is true, return 0, if false, return non-zero
echo $? If
non-zero is false, 0 is true
. There must be spaces on both sides of the conditional expression

Judge the integer
-gt: greater than
test 1 -gt 2 or abbreviated as 1 -gt 2
echo $?
1 is false, 0 is true
-ge: greater than or equal to
-eq: equal to
-le: less than or equal to
-lt: less than
-ne: not equal to
Judgment expression
-a: Both conditions are satisfied
----------and
-o: Only one condition is satisfied
----------or

String comparison
[[ -z $str ]] //Length is 0, return 0
[[ $str1 == $str2 ]]//Judging whether they are equal
[[ $str1 != $str2 ]]

File condition test
-f -L -d -e
-w -r -x
Insert picture description here
5. Process control
if then else
if [condition 1]
then
command 1
elif [condition 2]
then
command 2

else
command n
fiInsert picture description here

#!/bin/bash
echo "请输入1-7的整数"
read num
if [ $num == 1 ]
then
	echo "今天星期一"
elif [ $num == 2 ]
then
	echo "今天星期二"
else
	echo "输入错误"

fi

case
case $ variable in
“1”)
command 1
;;
“2”)
command 2
;;
esac
Insert picture description here

#!/bin/bash
echo "请输入1-7的整数"
read num
case $num in
"1")
	echo "今天星期一"
	;;
"2")
	echo "今天星期二"
	;;
*)
	echo "输入错误"
	;;
esac

for
form one
for x in list
do
command
done

Insert picture description here

#!/bin/bash
for x in 1 2 3 4 5
do
	echo "hello world"
done

seq command:

`seq  1 10` #执行10

Form two
for ((i=0;i<5;i++))
do
statement
done

#!/bin/bash
for x in `seq 1 10`  #小撇号作用:引用系统指令
do
	echo "hello world"
done

Another way of writing:

#!/bin/bash
for((i=0;i<5;i++))
do
	echo "hello world"
done

while
while [loop condition]
do
command
done
Insert picture description here

#!/bin/bash
echo "请输入整数"
read num
while [ $num -lt 10 ]
do
	echo "hello"
	num=$(($num+1))
done

supplement:
Method to exit the infinite loop:
Method one:

ctrl+c

Method 2:

ps -ef //查看当前进程
找到进程号
kill -9 30312   //杀死进程

until
until conditional
do
command
done
Insert picture description here

#!/bin/bash
echo "请输入整数"  //大于10
read num
until [$num -lt 10]
do
	echo "hello"
	num=$(($num-1))
done

break continue
Insert picture description here

#!/bin/bash
for ((i=0;i<5;i++))
do
	echo "hello world"   //打印4次
if (($i==3))
then
	break   //continue打印5次
fi
done

6. Array
definition

Definition 1: a=(1 2 3 4 5) The subscript starts from 0 and each data is separated by a space.
Definition 2: a[0]=1;a[1]=2;a[2]=
3Definition 3 : A=([1]=1 [2]=2)

Quote

Value: ${a[0]}
${a[@]} //Take all the values ​​in the array
${#a[@]} //Take the length of the array
${a[@]:2} // Intercept all elements with subscript 2 and later
${a[@]:2:2} //Intercept 2 elements with subscript 2 and later

#!/bin/bash
a=(1 2 3 4 5 6)
echo ${
    
    a[0]}  //打印1
echo ${
    
    a[@]}  //1 2 3 4 5 6
echo ${
    
    #a[@]}    //6
echo ${
    
    a[@]:2}    // 3 4 5 6
echo ${
    
    a[@]:2:2}    // 3 4 

7. Function

Just write the function name when calling, no return value, no parameters, just to encapsulate the code
function_name()
{}

#!/bin/bash
fun()
{
    
    
	echo "hello"
}
fun

8. Application of shell programming:
8.1, find all .c files in the current path:

#!/bin/bash
#简化版的查找.c文件的shell脚本
#寻找.c文件的函数(function )
findcfile()
{
    
    
#找到以.c结尾的文件,文件名列表存放在变量cfilelist里边
 cfilelist=$(ls | grep '.c$') 
#通过for循环显示文件路径以及文件名
 for cfilename in $cfilelist
 do
  echo $(pwd)/$cfilename
 done
}
#调用函数实现查找
echo "当前路径下的.c文件有:"
findcfile

Insert picture description here
You can find out all the .c files in the current path.

8.2. Find all the .c files in the current path and folder.

#!/bin/bash
#完整版的查找.c文件的shell脚本,可以进入文件夹
#判断通过参数传递的文件夹是否存在,是否为空
if [[ -z $1 ]] || [[ ! -e $1 ]]
then
#如果没有传递文件夹,就在当前目录下寻找
 echo "The directory is empty or not exist!"
 echo "It will use the current directory."
 newdir=$(pwd) //引用当前路径给变量
 echo "当前所在路径是:"
 echo $newdir
 echo "这个路径下.c文件有:"
else
#如果传递的有文件夹,进入传递的文件夹,开始寻找
cd $1  
 newdir=$(pwd)
 echo "当前所在路径是:"
 echo $newdir
 echo "这个路径下.c文件有:"
fi
#递归寻找.c文件的函数
findcfile()
{
    
    
#找到以.c结尾的文件,文件名列表放存在变量cfilelist里边
 cfilelist=$(ls | grep '.c$') 
#通过for循环显示文件路径以及文件名
 for cfilename in $cfilelist
 do
  echo $(pwd)/$cfilename
 done
 #遍历该目录,当判断其为目录的时候,进入目录,调用该函数,实现递归
 dirlist=$(ls)
 for dirname in $dirlist
 do
  if [ -d $dirname ]
  then
   cd $dirname
   findcfile
   cd ..   //返回上层目录
  fi
 done
}
#调用递归函数实现查找
findcfile

Insert picture description here
You can print out all the .c files.

Reference structure flow chart:
shell programming
Note: need to use xmind software to view

Guess you like

Origin blog.csdn.net/weixin_40734514/article/details/108947860