Shell Script Study

Basic learning of shell script

Posted by Boyu Cai on Monday, April 18, 2022

Shell

Shell 简介

Linux 系统界面,而不涉及到Linux内核

shell 脚本 = shell命令+ shell特性 + 流程控制

流程

  1. 用户输入命令
  2. 解释命令
  3. 在内核中执行然后返回结果

命令学习

man [command] # 帮助命令

管理文件

  • cd pwd mkdir rmdir
  • touch cp mv rm file cat more less tail head

管理进程

  • ps top kill killall

管理磁盘空间

  • mount umount df du

处理数据文件

  • sort grep azip tar

Shell 中的变量

# 环境变量
set

变量的定义与赋值

val=value

**注意:**等号两边不能有空格

变量

echo ${name}

输出赋值给变量

YYYYMMDD=$(date +%Y%m%d)

Shell 条件控制

基本格式:

if command
then
	commands1
else
	commands2
fi

条件测试格式:

if [ 1 -eq 2 ] # 条件测试
then
	echo "equal"
else
	echo "not equal"
fi

注意:

  • 左右方括号之间要留空格

数值比较

n1-eq n2	# 相等
-ge	# 大于等于
-gt	# 大于
-le	# 小于等于
-lt	# 小于
-ne # 不等于

字符串

=
!=
>
<
-n # 长度不为0
-z # 长度是否为0

文件比较

-d file # 存在目录
-f	# 存在文件
-r	# 可读
-s	# 非空
-w	# 可写
-x	# 可执行
file1 -nt file2 # 1比2新(备份)
-ot

case语句

case expression in
	pattern1)
		commands1;;
	pattern2)
		commands2;;
	pattern3)
		commands3;;
	*)
		default commands;;
esac

练习:

image-20220418105005895

#!/bin/sh

case $1 in
	'sysinfo')
		uname -a
		exit
		;;
	'user')
		pwd
		whoami
		exit
		;;
	'add')
		sum=$(($2+$3))
		echo ${sum}
		exit
		;;
	'judge')
		if [ "$2"="man" ];then 
			if [ $3 -gt 175 ];then
				echo "above average"
			elif [ $3 -eq 175 ];then
				echo "average"
			else
				echo "blow average"
			fi
		else
			if [ $3 -gt 165 ];then
				echo "above average"
			elif [ $3 -eq 165 ];then
				echo "average"
			else
				echo "blow average"
			fi
		fi
		exit
		;;
	*)
		default exit
		;;
esac	

DBug:

  1. 注意编写格式

  2. 注意每个条件后添加 exit

  3. 判断条件测试

    1. 字符串判断

      [ "$A"="$B" ]
      
    2. 数值判断

      [ a -gt b]