SHELL Basics 01

1. What is shell?

			答:shell是用来与linux内核之间的解释器

1. Common shell interpreters:

/bin/bash
/bin/sh
/bin/csh
/bin/tcsh
			解释器负责将用户的指令翻译为内核可以识别的命令
			通过usermod、chsh可以更改登录SHELL

2. Check which shell the user uses through /etc/password

[root@localhost ~]# grep test /etc/passwd
test:x:1000:1000::/home/test:/bin/bash

3. View the shell in the current computer

[root@localhost ~]# cat /etc/shells 
/bin/sh
/bin/bash
/sbin/nologin
/usr/bin/sh
/usr/bin/bash
/usr/sbin/nologin

4. Install the interpreter (SHELL) you need

yum -y install tcsh

5. Modify the user interpreter (shell)

[root@localhost ~]# usermod -s /bin/tcsh test
[root@localhost ~]# grep test /etc/passwd
test:x:1000:1000::/home/test:/bin/tcsh

 或
 
[root@localhost ~]# chsh -s /bin/bash test 
Changing shell for test.		//正在修改test的解释器
Shell changed.			//修改完成
[root@localhost ~]# grep test /etc/passwd
test:x:1000:1000::/home/test:/bin/bash

Bash basic features

				快捷键、Tab键补齐
				命令历史(history)
				命令别名(aliase)
				标准输入与输出的重定向{>正常输出、>>追加、2>错误输出、2>>错误追加输出、&>错误正确全输出}
				管道( | )

Shell execution command mode

- 交互式(命令行)
	- 人工干预
	- 一条条解析执行、效率低
- 非交互式(脚本)
	- 需要提前设计
	- 批量执行、效率高

Case 1: Modify the user’s shell interpreter

#yum安装一个新的解释器ksh,通过cat /etc/shells确认

[root@localhost ~]# yum -y install ksh
[root@localhost ~]# cat /etc/shells 
    /bin/sh
    /bin/bash
    /sbin/nologin
    /usr/bin/sh
    /usr/bin/bash
    /usr/sbin/nologin
    /bin/ksh
    /bin/rksh

#使用useradd创建用户(natasha)并指定登录shell为/bin/ksh
[root@localhost ~]# useradd natasha -s /bin/ksh 
[root@localhost ~]# cat /etc/passwd | grep natasha
natasha:x:1000:1000::/home/natasha:/bin/ksh

#使用usermod修改natasha账户的登录Shell为/bin/bash
[root@localhost ~]# usermod -s /bin/bash natasha
[root@localhost ~]# cat /etc/passwd | grep natasha
natasha:x:1000:1000::/home/natasha:/bin/bash 

2. Script design and execution

什么是SHELL脚本
	答:脚本是提前将可执行的命令语句写入一个文件中,按顺序执行、解释器剢行解释代码。
常见的脚本:
	Shell脚本
	Python/Perl/Ruby脚本
	JSP/PHP脚本
#编写第一个hello word脚本
	#1、新建文档
	#2、添加可执行语句(命令)
	#3、给文件添加X执行权限
	
[root@localhost ~]# mkdir -p /root/shell/day01		//day01是第一天的目录第二dat02.。。。dat10
[root@localhost ~]# vim /root/shell/day01/first.sh		//执行输出hello world
 echo "hello world"					
[root@localhost ~]# chmod +x /root/shell/day01/first.sh 	//脚本添加执行权限
[root@localhost ~]# /root/shell/day01/first.sh 		//绝对路径执行脚本
    hello world
[root@localhost day01]# ./first.sh 			//相对路径执行脚本./是当前目录
hello world

Standard script composition

#一个合格规范的脚本应该包含以下这些内容
##!脚本声明(使用那种解释器解释代码)
#注释信息(步骤、思路、用途等),以#开始的为注释信息
#可执行的语句

[root@localhost day01]# vim first.sh 
    #!/bin/bash					//脚本声明
    #shuchu "hello world"				//注释信息(输出“hello world”)
    echo "hello world"                                      
[root@localhost day01]# ./first.sh 		//执行脚本
    hello world

Multiple ways to execute scripts

	方法一:需要为文件赋予可执行的权限
			绝对路径执行
			相对路径执行
	方法二:不需要文件有可执行的权限
			sh   脚本文件名
			source	脚本文件名		#不会启动子进程,通过pstree查看进程树。如果系统没有pstree命令使用yum安装psmisc
进程讲解:
    使用source执行脚本的时候没有子进程当你执行exit的时候加入您是用Xshell登录的会退出Xshell
    使用sh执行脚本的时候会生成一个子进程当你执行exit的时候会先退出sh生成的子进程,Xshell不会退出			

Case 2: Writing test scripts

#编写一个屏幕显示Hello Word的脚本
[root@localhost day01]# vim first.sh 
        #!/bin/bash
        #shuchu "hello world"
        echo "hello world"		

#使用多种方式执行该脚本
##需要有执行权限
[root@localhost day01]# chmod +x first.sh 
[root@localhost day01]# ./first.sh 
hello world
[root@localhost day01]# /root/shell/day01/first.sh 
hello world
 
##可以没有执行权限
[root@localhost day01]# sh first.sh 
hello world
[root@localhost day01]# source first.sh 			//没有子进程
hello world

#测试source脚本文件与其他方式执行脚本的差异
[root@localhost day01]# vim sleep.sh			//沉睡100秒脚本
    #!/bin/bash
    
sleep 100
[root@localhost day01]# chmod +x sleep.sh 

再开一个终端:
1、使用sh执行脚本
[root@localhost ~]# pstree			
├─sshd─┬─sshd───bash───sh───sleep		//生成了一个sh子进程
│      └─sshd───bash───pstree

 
2、使用source执行脚本
[root@localhost ~]# pstree			
├─sshd─┬─sshd───bash───sleep		//不会生成子进程
│      └─sshd───bash───pstree

3. Variables

1. Custom variables

(1) Define variables
以固定的名称,存放可以能有变化的值
等于变量的格式:
		变量名=变量值
取消变量的格式:
		unset 变量名
注意事项:
		=两边不能有空格,不要使用关键字做变量名,如ls、cd等
		如果变量名已经存在则覆盖之前的变量值
		变量名称有:字母/数字/下划线组成,不能以数字开始
(2) View variables:
查看变量的语法格式:
	$变量名
	${变量名}
[root@localhost day01]# x=centos		//x变量值为centos
[root@localhost day01]# echo $x		//输出x变量
    centos
[root@localhost day01]# echo ${x}		//输出x变量
    centos
[root@localhost day01]# echo ${x}6.5	//如果后面想输出问centos6.5则用花括号
    centos6.5
[root@localhost day01]# unset x		//取消变量,在脚本中不需要unse取消

2. System default variables

(1) Environment variables
环境变量(变量名通常大写,操作系统定义的,有操作系统维护)
位置变量(bash内置变量,存储脚本执行时的参数)
预定义变量(bash内置变量,可以调用但是不能赋值或修改)
自定义变量(用户自主设置)
(2) Environment variables
存储在/etc/profile或~/.bash_profile
命令env可以列出所有的环境变量
常见环境变量:
		   PATH、PWD、USER、UID、HOME、SHELL
[root@localhost day01]# echo $PATH					//PATH变量又叫命令搜索路径(搜索路径用的)
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
[root@localhost day01]# echo $PWD					//显示当前路径的变量
/root/shell/day01	
[root@localhost day01]# echo $USER					//显示当前用户的变量
root
[root@localhost day01]# echo $UID					//显示当前用户的UID
0
[root@localhost day01]# echo $HOME					//显示当前用户的家目录
/root
[root@localhost day01]# echo $SHELL				//显示当前用户的shell环境
/bin/bash

(3) Position variable

存储脚本执行时的参数
使用$n表示,n为数字序列号
$1、$2、......、${10}、${11}、...			//当数字大于9的时候需要使用花括号
实例1:
[root@localhost day01]# vim vars.sh
  #!/bin/bash
  echo $1
  echo $2
  echo $3
  
[root@localhost day01]# chmod +x vars.sh 
[root@localhost day01]# ./vars.sh aa bb cc 		//执行脚本的时候aa对应的是脚本中的$1,bb=$2,cc=$3
aa
bb
cc


实例2:
[root@localhost day01]# vim /root/shell/day01/user.sh
[root@localhost day01]# chmod +x user.sh 
  #!/bin/bash
  
useradd "$1"
  echo "$2" | passwd --stdin "$1"
[root@localhost day01]# ./user.sh tom 123456
Changing password for user tom.
passwd: all authentication tokens updated successfully.
[root@localhost day01]# grep tom /etc/passwd
tom:x:1001:1001::/home/tom:/bin/bash

(4) Predefined variables

用来保存脚本程序的执行信息
		直接使用这些变量
		不能直接为这些变量赋值
variable name meaning
$0 The current process or script name
$$ PID number of the currently running process
$? Return status after command execution, 0 means normal, 1 or other value means abnormal
$# The number of loaded position variables
$* The value of all position variables
#测试预定义变量
[root@localhost ~]# ls /opt/
[root@localhost ~]# echo "$?"		//显示0说名ls /opt/执行成功
0
[root@localhost ~]# ls /123q23423		
ls: cannot access /123q23423: No such file or directory
[root@localhost ~]# echo "$?"		//显示非0表示上一条执行失败
2

[root@localhost ~]# vim /root/shell/day01/pre.sh
#!/bin/bash

echo $0
echo $$
echo $#
echo $*
[root@localhost ~]# chmod +x /root/shell/day01/pre.sh 

[root@localhost ~]# /root/shell/day01/pre.sh aa bb cc d4
/root/shell/day01/pre.sh		//$0显示的是脚本自己的名称
2546				//$$显示的脚本进程号
4					//$#显示的是脚本位置参数个数
aa bb cc d4			//$*显示所有位置变量的值
# #案例3:变量的应用
		#熟悉自定义变量的用法
        #熟悉环境变量
        #熟悉位置变量
        #熟悉预定义变量

4. Variable expansion application

1. Various quotation marks:

(1) The difference between various quotation marks

 区分三种定界符
	双引号 " ":允许扩展,以 $ 引用其他变量
	单引号 '  ':禁用扩展,即便 $  也视为普通字符
	反引号 ` `:将命令的执行输出作为变量值,$() 与反引号等效
 #不加引号和加引号的区别
 [root@localhost ~]# touch a b c 		//不加引号创建了三个文件
[root@localhost ~]# touch "a b c"		//加引号创建了一个文件(单引号和双引号都是一样的)
[root@localhost ~]# ll
total 4
-rw-r--r--  1 root root    0 Dec 22 17:23 a
-rw-r--r--  1 root root    0 Dec 22 17:23 a b c
-rw-------. 1 root root 1260 May 20  2021 anaconda-ks.cfg
-rw-r--r--  1 root root    0 Dec 22 17:23 b
-rw-r--r--  1 root root    0 Dec 22 17:23 c
drwxr-xr-x  3 root root   19 Dec 21 15:56 shell
[root@localhost ~]# rm -rf a b c		//这样删除的时候是删除了三个文件
[root@localhost ~]# ll
total 4
-rw-r--r--  1 root root    0 Dec 22 17:23 a b c
-rw-------. 1 root root 1260 May 20  2021 anaconda-ks.cfg
drwxr-xr-x  3 root root   19 Dec 21 15:56 shell
[root@localhost ~]# rm -rf "a b c"		//这样才能把a b c这个文件删除用来一个引体
[root@localhost ~]# ls
anaconda-ks.cfg  shell

[root@localhost ~]# hi="world"
[root@localhost ~]# echo "$hi"		//双引号会把$视为变量的值
world
[root@localhost ~]# echo '$hi'		//单引号会把$视为普通字符
$hi

[root@localhost ~]# echo "$USER id is $UID"	//获取当前用户的用户名和ID值
root id is 0
[root@localhost ~]# echo '$USER id is $UID'	//单引号会原封不动的输出
$USER id is $UID

[root@localhost ~]# grep root /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
[root@localhost ~]# test=`grep root /etc/passwd`
[root@localhost ~]# echo "$test"
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
[root@localhost ~]# test1=$(grep tom /etc/passwd)
[root@localhost ~]# echo $test1
tom:x:1001:1001::/home/tom:/bin/bash

2. Read command predefined variables

(1) read standard input value

格式: read  [-p  "提示信息" ]  变量名
-p 可选,-t 可指定超时秒数,-s 设置是否在终端显示输入的内容
[root@localhost ~]# vim /root/shell/day01/read.sh
[root@localhost ~]# chmod +x /root/shell/day01/read.sh 
#!/bin/bash

read -p "请输入用户名:" name
read -p   "请输入密码:" pass
useradd "$name"
echo "$pass" | passwd --stdin "$name"
[root@localhost ~]# /root/shell/day01/read.sh 
请输入用户名:user10
请输入密码:123456
Changing password for user user10.
passwd: all authentication tokens updated successfully.
#这样密码是显示出来的不安全修改进行修改脚本

[root@localhost ~]# vim /root/shell/day01/read.sh 
#!/bin/bash

read -p "请输入用户名:" name
read -s -p  "请输入密码:" pass			//注意这里加了-s参数
useradd "$name"
echo "$pass" | passwd --stdin "$name"
[root@localhost ~]# chmod +x /root/shell/day01/read.sh 
[root@localhost ~]# /root/shell/day01/read.sh 
请输入用户名:zhangsan
请输入密码:				//这里已经输入密码隐藏了
Changing password for user zhangsan.
passwd: all authentication tokens updated successfully.

3. Global OR local

(1) Scope of variables

局部变量
	新定义的变量默认只在当前SHell环境中有效,无法在子Shell环境中使用
全局变量
	全局变量在当前shell及子Shell环境中均有效
#局部变量
[root@localhost ~]# x=11
[root@localhost ~]# echo $x
11
[root@localhost ~]# sh

sh-4.2# echo $x

#全局变量
[root@localhost ~]# export a=22
[root@localhost ~]# echo $a
22
[root@localhost ~]# sh
sh-4.2# echo $a
22
# 案例2:变量的扩展应用
#熟悉三种引号的区别
#通过read定义变量
#熟悉局部变量与全局变量的区别

5. Operations in shell

1. Integer operations

(1) Basic operation rules

四则运算
	加法:   num1 + num2
	减法:	  num1 - num2
	乘法:    num1 * num2
	整除:	  num1 / num2
取余数运算
	求模:	  num1   %   num2

(2) $[] formula replacement

使用 $[ ] 或 $(( )) 表达式
	格式: $[ 整数1    运算符   整数2  ..  ..  ]
	计算结果替换表达式本身,可结合 echo 命令输出
# 四则运算
[root@localhost ~]# echo $[1+8]
9
[root@localhost ~]# echo $[9-1]
8
[root@localhost ~]# echo $[2*8]
16
[root@localhost ~]# echo $[10/5]
2
 
# 取余数运算
[root@localhost ~]# echo $[10%2]
0
[root@localhost ~]# echo $[10%3]
1
 
# 设置变量进行四则运算
[root@localhost ~]# x=2
[root@localhost ~]# y=3
[root@localhost ~]# echo $[x+y]
5
[root@localhost ~]# echo $[x*y]
6

(3) Operations such as automatic increment/decrement of variables

shorthand expression complete expression
i++ i=i+1
i– i=i-1
i+=2 i=i+2
i-=2 i=i-2
i*=2 i=i*2
i/=2 i=i/2
i%=2 i=i%2
[root@localhost ~]# x=2
[root@localhost ~]# echo $[x+=4]			//相当于x=2+4
6
[root@localhost ~]# echo $x			//自增之后值会变
6
[root@localhost ~]# echo $[x+=1]
7
[root@localhost ~]# echo $[x*=3]
21
 
# let 命令也可以加减乘除只是不显示结果要想显示结果需要另输入“echo”  命令
[root@localhost ~]# let i=2*3
[root@localhost ~]# echo $i
6
[root@localhost ~]# let i=3*6

[root@localhost ~]# echo $i
18
#let也可以使用简写格式
[root@localhost ~]# i=2
[root@localhost ~]# let i+=2
[root@localhost ~]# echo $i
4
[root@localhost ~]# let i*=3
[root@localhost ~]# echo $i
12

2. Decimal operations

(1) bc calculator

Bash内建机制仅支持整数运算,不支持小数运算

Insert image description here

[root@localhost ~]# echo $[3.5+3.2]
-bash: 3.5+3.2: 语法错误: 无效的算术运算符 (错误符号是 ".5+3.2")
		我们可以通过计算器软件bc实现小数运算
			如果没有该软件则需要使用yum安装
			bc支持交互式和非交互式两种方式计算,scale=n 可以约束小数位
# 交互运行
[root@localhost ~]# bc
bc 1.06.95
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'. 
1.5+2.3
3.8
2.5*2.6
6.5
10/2
5
scale=2
10/2
5.00
quit
 
 
# 非交互运算
[root@localhost ~]# echo "1.2+3.3" | bc			//单个运算
4.5	

[root@localhost ~]# echo "1.2+3.3;3.8*2.7" | bc		//多个运算
4.5
10.2
[root@localhost ~]# echo "scale=2;10/2" | bc		//指定小数点位数
5.00

3. Decimal comparison

(1) Comparison operators supported by bc: >, >=, <, <=, ==, !=

表达式成立则返回1,否则返回0
[root@localhost ~]# echo "1>2" | bc
0
[root@localhost ~]# echo "1<2" | bc		//对的返回1
1
运算练习
	掌握如何在Shell脚本中运行整数运算
	掌握如何在Shell脚本中运行小数运算
	掌握如何在Shell脚本中运行算术比较

6. Comprehensive cases

1. Monitoring script to display hardware information

	echo回显
		-n 选择:不换行
		-e 选项:支持扩展属性
[root@localhost day01]# echo "hello world"			//换行
hello world
[root@localhost day01]# echo -n "hello world"		//不换行
hello world[root@localhost day01]# 
 
\033:开启颜色属性[31m:颜色色号OK:要显示的信息\033:结束颜色属性[0m:回归黑色。三十多是字体颜色四十多是背景颜色
[root@localhost day01]# echo -e "\033[31mOK\033[0m"	//红色显示OK
OK	
[root@localhost day01]# echo -e "\033[32mOK\033[0m"	//绿色显示OK
OK
[root@localhost day01]# echo -e "\033[33mOK\033[0m"	//蓝色显示OK
OK

Monitor hardware information

[root@localhost day01]# vim info.sh
#!/bin/bash
#显示服务器硬件信息。
echo -e "\033[34m----------服务器硬件信息-----------\033[0m"
echo -e "\033[32m网卡信息如下:\033[0m"
ifconfig ens33 | grep "inet "

echo -e "\033[32m剩余内存容量信息如下:\033[0m"
grep MemAvailable /proc/meminfo

echo -e "\033[32m磁盘容量信息如下:\033[0m"
df -h /

echo -e "\033[32mCPU信息如下:\033[0m"
grep "model name" /proc/cpuinfo

[root@localhost day01]# chmod +x info.sh 
[root@localhost day01]# ./info.sh 
----------服务器硬件信息-----------
网卡信息如下:
        inet 192.168.1.110  netmask 255.255.255.0  broadcast 192.168.1.255
剩余内存容量信息如下:
MemAvailable:    1594416 kB
磁盘容量信息如下:
Filesystem           Size  Used Avail Use% Mounted on
/dev/mapper/cl-root   17G  1.7G   16G  10% /
CPU信息如下:
model name	: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz

2. Calculation exercises

(1) Data calculation

[root@localhost day01]# vim calc.sh
#!/bin/bash
#计算1+2+3,....,+n的和,可以使用n*(n+1)/2公式快速计算结果
read -p "请输入一个正整数:" num
sum=$[num*(num+1)/2]
echo -e "\033[32m$num以内整数的总和是:$sum\033[0m"

#请使用三角形的底边和高计算面积:A=1/2bh(b是底边长度h是高度)
read -p "请输入三角形底边长度:" bottom
read -p "请输入三角形高度:" hight
A=$(echo "scale=1;1/2*$bottom*$hight" | bc)
echo -e "\033[32m三角形面积是:$A\033[0m"

#梯形面积:(上底边长度+下底边长度)*高/2
read -p "请输入梯形上底边长度:" a
read -p "请输入梯形下底边长度:" b
read -p "请输入梯形高度:" h
A=$(echo "scale=2;($a+$b)*$h/2" | bc)
echo -e "\033[32m梯形面积是:$A\033[0m"

#使用A=πr2公式计算圆的面积,取2位小数点精度,π=3.14
read -p "请输入圆的半径:" r
A=$(echo "scale=2;3.14*$r^2" | bc)
echo -e "\033[32m圆的面积是:$A\033[0m"


[root@localhost day01]# chmod +x calc.sh 
[root@localhost day01]# ./calc.sh 
请输入一个正整数:100
100以内整数的总和是:5050
请输入三角形底边长度:3
请输入三角形高度:5
三角形面积是:7.5
请输入梯形上底边长度:5
请输入梯形下底边长度:3
请输入梯形高度:2
梯形面积是:8.00
请输入圆的半径:60
圆的面积是:11304.00

3. Automatically configure YUM source

Configure YUM source script

[root@localhost day01]# vim yum.sh
#!/bin/bash
#定义YUM源路径
URL=ftp://192.168.1.110/centos

#创建YUM源配置文件
echo "[Centos]
name=centos
baseurl=$URL
gpgcheck=0" > /etc/yum.repos.d/iyum.repo

[root@localhost day01]# chmod +x yum.sh 
[root@localhost day01]# ./yum.sh 
[root@localhost day01]# cat /etc/yum.repos.d/iyum.repo 
[Centos]
name=centos
baseurl=ftp://192.168.1.110/centos
gpgcheck=0
# 案例6:综合案例
#服务器监控脚本之硬件信息
#各种数学计算的练习题
#自动创建yum源配置文件

Guess you like

Origin blog.csdn.net/weixin_46010834/article/details/122209906