day028-Shell自动化编程-判断进阶

文章目录

  • 1. 特殊变量补充
  • 2. 变量扩展-变量子串
    • 2.1 获取变量字符的长度
    • 2.2 给变量设置默认值
  • 3. 命令
    • 3.1 dirname
    • 3.2 basename
    • 3.3 cut
  • 4. 条件测试命令:[]
    • 4.1 逻辑运算符
    • 4.2 文件测试
    • 4.3 案例:书写脚本-检查文件类型
    • 4.4 逻辑运算
    • 4.5 案例:书写脚本-检查服务是否正在运行或是开机自启动
    • 4.6 增强版条件测试命令:[[]]
    • 4.7 面试题:[]与[[]]的区别?
  • 5. 字符串比较
    • 5.1 案例:书写脚本-检查服务是否正在运行和开机自启动
  • 6. 多分支:if、case
    • 6.1 案例-统计根分区磁盘使用率,60-70输出警告,70-80输出需要处理,80-95输出需要及时处理,965以上输出立刻处理
    • 6.2 案例:判断系统类型
  • 7. 踩坑记录
    • 1. 条件测试时,变量要加上双引号
  • 8. 思维导图

1. 特殊变量补充

  • $$:获取当前脚本的pid
  • $_:获取上一个命令的最后一个参数;在命令行中可以使用Esc+.快捷键

2. 变量扩展-变量子串

  • 用于对变量处理、加工

2.1 获取变量字符的长度

[root@aliyun-ubuntu ~]# name=skx
[root@aliyun-ubuntu ~]# echo $name
skx
[root@aliyun-ubuntu ~]# echo ${#name}
3

2.2 给变量设置默认值

格式说明
${para:-word}变量para没定义或为空时,word作为默认值,不修改原内容
${para:=word}变量para没定义或为空时,word作为默认值,修改原内容
  • ${para:-word}
# 变量为空
[root@aliyun-ubuntu ~]# echo $name# 为变量设置默认值,不修改原内容
[root@aliyun-ubuntu ~]# echo ${name:-root}
root
[root@aliyun-ubuntu ~]# echo $name
  • ${para:=word}
[root@aliyun-ubuntu ~]# echo $name # 为空变量设置默认值,并修改原内容
[root@aliyun-ubuntu ~]# echo ${name:=skx}
skx
[root@aliyun-ubuntu ~]# echo $name
skx

3. 命令

3.1 dirname

  • 显示路径前缀
[root@aliyun-ubuntu ~]# dirname /etc/passwd
/etc
[root@aliyun-ubuntu ~]# dirname /etc/ssh/ssh_config
/etc/ssh

3.2 basename

  • 显示路径后缀
[root@aliyun-ubuntu ~]# basename /etc/passwd
passwd
[root@aliyun-ubuntu ~]# basename ./snap/lxd/
lxd

3.3 cut

  • -c n-m:截取字符串的第n到第m个字符
[root@aliyun-ubuntu ~]# string=1234567890
[root@aliyun-ubuntu ~]# echo $string |cut -c 5
5
[root@aliyun-ubuntu ~]# echo $string |cut -c 5-8
5678

4. 条件测试命令:[]

[ ]或test,用于检查文件属性、字符串比较、数值比较等逻辑判断。它是 Shell 脚本中常见的条件判断语法之一。

  • []内部必须用空格分隔

4.1 逻辑运算符

  • 逻辑运算符不能在[]内使用
  • &&:并且,前面命令执行成功后才执行后面的命令
  • ||:或者,前一个命令执行失败后才执行后面的命令

4.2 文件测试

选项说明
-f文件是否为普通文件
-d文件是否为目录
-x文件是否有执行权限
-s文件大小大于0
-h/-L文件是否为软链接
[root@aliyun-ubuntu ~]# [ -f ./passwd.txt ] && echo file || echo 'not file'
file
[root@aliyun-ubuntu ~]# [ -d /etc/ ] && echo dir || echo 'not dir'
dir
[root@aliyun-ubuntu ~]# [ -d /etc/passwd ] && echo dir || echo 'not dir'
not dir

4.3 案例:书写脚本-检查文件类型

[root@aliyun-ubuntu /server/scripts]# cat check_type.sh 
#!/bin/bash
##############################################################
# File Name: check_type.sh
# Version: V1.0
# Author: SunKexu
# Organization: www.oldboyedu.com
# Description:test file type
##############################################################
export LANG=en.US_UTF-8# vars
file=$1
# command
# check param num
if [ $# -eq 0 ];thenecho "Usage:$0 file/dir"exit 1
fi
# soft link
if [ -h $file ];thenecho "$file is symbolic"exit 0
fi
# file
if [ -f $file ];thenif [ -x $file ];thenmode="has permisson"else mode="has not permission"fiif [ -s $file ];thensize="size not is 0"elsesize="size is 0"fiecho "${file} is file;permission:${mode};size:${size}"exit 0
fi
# dir
if [ -d $file ];thenecho "$file is directory"exit 0
fiecho "$file is other type file"
[root@aliyun-ubuntu /server/scripts]# bash check_type.sh
Usage:check_type.sh file/dir
[root@aliyun-ubuntu /server/scripts]# bash check_type.sh /sbin
/sbin is symbolic
[root@aliyun-ubuntu /server/scripts]# bash check_type.sh ./check_type.sh 
./check_type.sh is file;permission:has not permission;size:size not is 0
[root@aliyun-ubuntu /server/scripts]# bash check_type.sh /usr/   
/usr/ is directory
[root@aliyun-ubuntu /server/scripts]# bash check_type.sh ./test
./test is other type file

4.4 逻辑运算

逻辑运算符说明
-a并且
-o或者
取反

4.5 案例:书写脚本-检查服务是否正在运行或是开机自启动

[root@aliyun-ubuntu /server/scripts]# cat check_service2.sh 
#!/bin/bash
##############################################################
# File Name: check_service2.sh
# Version: V1.0
# Author: SunKexu
# Organization: www.oldboyedu.com
# Description:
############################################################### vars
name=$1
# command
if [ $# -eq 0 ];thenecho "Usage:$0 server name"exit 1
firunning=`systemctl is-active $name`
enable=`systemctl is-enabled $name`
if [ ${running}="active" -a ${enable}="enabled" ];thenecho "$name is running and enabled"
elseecho "$name is not running or enabled"
fi
[root@aliyun-ubuntu /server/scripts]# bash check_service2.sh
Usage:check_service2.sh server name
[root@aliyun-ubuntu /server/scripts]# bash check_service2.sh sshd
sshd is running and enabled

4.6 增强版条件测试命令:[[]]

[[ ]],比 [] 更强大,支持 &&||、正则匹配等

  • 正则匹配符号:=~,前后要有空格
[root@aliyun-ubuntu /server/scripts]# id=678
[root@aliyun-ubuntu /server/scripts]# [[ "$id" =~ [0-9]+ ]] && echo 1 || echo 2
1
[root@aliyun-ubuntu /server/scripts]# name=skx123
[root@aliyun-ubuntu /server/scripts]# [[ "$name" =~ [0-9]+ ]] && echo 1 || echo 2
1
[root@aliyun-ubuntu /server/scripts]# [[ "$name" =~ ^[0-9]+$ ]] && echo 1 || echo 2
2

4.7 面试题:[]与[[]]的区别?

基本条件测试命令:[]扩展条件测试命令:[[]]
无法使用正则可以使用正则
只能使用选项比价大小:-eq、-lt、-gt……可以使用选项,也能用字符:==、>=、<=……
逻辑符号只能用-a、-o、!逻辑符号可以用&&、||、!,不能用选项

5. 字符串比较

符号说明
=“字符串” = “字符串”,注意加双引号和空格
!=判断不相等
-zzero,判断变量是否为空格
-nnot zero,判断变量是否不为空
[root@aliyun-ubuntu /server/scripts]# [ 123=123 ] && echo 1 || echo 2
1
[root@aliyun-ubuntu /server/scripts]# name="skx"
[root@aliyun-ubuntu /server/scripts]# [ ${name}="skx" ] && echo 1 || echo 2
1

5.1 案例:书写脚本-检查服务是否正在运行和开机自启动

[root@aliyun-ubuntu /server/scripts]# cat check_service.sh
#!/bin/bash
##############################################################
# File Name: check_service.sh
# Version: V1.0
# Author: SunKexu
# Organization: www.oldboyedu.com
# Description:check service status
##############################################################
export LANG=en.US_UTF-8# vars
service=$1# command
# check parameter num
if [ $# -eq 0 ];thenecho "Usage:$0 service name"exit 1
fi
# check running state
status_run=`systemctl is-active ${service}`
if [ ${status_run}="active" ];thenecho "${service} is running"
elseecho "${service} is not running"
fi# check enabled state
status_enabled=`systemctl is-enabled ${service}`
if [ ${status_enabled}="enabled" ];thenecho "${service} is enabled"
elseecho "${service} is not enabled"
fi
#####################################
if [ ${status_run}="active" -a ${status_enabled}="enabled" ];thenecho "$service is active and enabled"
fi
[root@aliyun-ubuntu /server/scripts]# bash check_service.sh sshd
sshd is running
sshd is enabled
sshd is active and enabled

6. 多分支:if、case

6.1 案例-统计根分区磁盘使用率,60-70输出警告,70-80输出需要处理,80-95输出需要及时处理,965以上输出立刻处理

[root@aliyun-ubuntu /server/scripts]# cat check_disk.sh
#!/bin/bash
##############################################################
# File Name: check_disk.sh
# Version: V1.0
# Author: SunKexu
# Organization: www.oldboyedu.com
# Description:
##############################################################export LANG=en.US_UTF-8# vars
usage=`df -h / |awk -F '[ %]' 'NR==2{print $(NF-2)}'`
# if
if [ $usage -gt 60 -a $usage -le 70 ];thenecho "Warning: Insufficient disk space ${usage}"
elif [ $usage -gt 70 -a $usage -le 80 ];thenecho "Warning: Insufficient disk space ${usage}"
elif [ $usage -gt 80 -a $usage -le 95 ];thenecho "Warning: Severe shortage of disk space ${usage}"
elif [ $usage -gt 95 ];thenecho "Warning: Disk space is about to run out ${usage}"
elseecho "Disk space is normal"
fi
[root@aliyun-ubuntu /server/scripts]# bash check_disk.sh
Disk space is normal

6.2 案例:判断系统类型

  • bash运行脚本是一个子shell程序,里面的变量仅在脚本中生效
  • source运行的脚本是在当前Shell环境,可以用来加载指定的变量
[root@aliyun-ubuntu /server/scripts]# cat check_os.sh
#!/bin/bash
##############################################################
# File Name: check_os.sh
# Version: V1.0
# Author: SunKexu
# Organization: www.oldboyedu.com
# Description:
##############################################################export LANG=en.US_UTF-8
# This file contains system version information
source /etc/os-release
# case
case "$ID" in kylin|rocky|centos) echo "$ID yum insatll package";;ubuntu|debian) echo "$ID apt install package";;*)echo "other system"esac[root@aliyun-ubuntu /server/scripts]# bash check_os.sh 
ubuntu apt install package

7. 踩坑记录

1. 条件测试时,变量要加上双引号

变量建议加引号

  • 如果变量可能为空或包含空格,必须加引号:
if [ "$var" = "hello" ]; then  # 正确
if [ $var = "hello" ]; then    # 如果 $var 为空,会报错

8. 思维导图

【金山文档】 思维导图 https://www.kdocs.cn/l/co3I7PtpTYQX

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.pswp.cn/diannao/86567.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

oracle sql 语句 优化方法

1、表尽量使用别名&#xff0c;字段尽量使用别名.字段名&#xff0c;这样子&#xff0c;可以减少oracle数据库解析字段名。而且把 不需要的字段名剔除掉&#xff0c;只保留有用的字段名&#xff0c;不要一直使用 select *。 2、关联查询时&#xff0c;选择好主表 。oracle解析…

【Java】Ajax 技术详解

文章目录 1. Filter 过滤器1.1 Filter 概述1.2 Filter 快速入门开发步骤:1.3 Filter 执行流程1.4 Filter 拦截路径配置1.5 过滤器链2. Listener 监听器2.1 Listener 概述2.2 ServletContextListener3. Ajax 技术3.1 Ajax 概述3.2 Ajax 快速入门服务端实现:客户端实现:4. Axi…

07 APP 自动化- appium+pytest+allure框架封装

文章目录 一、PO二、代码简单实现项目框架预览&#xff1a;base_page.pydir_config.pyget_data.pylogger.pystart_session.pyconfig.yamlkey_code.yamllaunch_page_loc.pylogin_page_loc.pylaunch_page.pylogin_page.pytest_login.pypytest.inirun.py APP 自动化代码总和 一、P…

用户体验升级:表单失焦调用接口验证,错误信息即时可视化

现代前端应用中&#xff0c;表单交互是用户体验的重要组成部分。而表单验证作为其中的核心环节&#xff0c;不仅需要前端的即时反馈&#xff0c;还需要与后端接口联动进行数据合法性校验。本文将详细介绍如何在Vue3中实现表单输入与接口验证的无缝联动&#xff0c;并优雅地展示…

Vue 插槽(Slot)用法详解

插槽(Slot)是Vue中一种强大的内容分发机制&#xff0c;它允许你在组件中定义可替换的内容区域&#xff0c;为组件提供了更高的灵活性和可复用性。本文将全面介绍Vue插槽的各种用法。 1. 基本插槽 基本插槽是最简单的插槽形式&#xff0c;它允许父组件向子组件插入内容。 子组…

C++ 标准模板库(STL)详解文档

C 标准模板库&#xff08;STL&#xff09;详解文档 1 前言2 常用容器2.1 内容总览2.2 向量 vector2.2.1 概述2.2.2 常用方法2.2.3 适用场景2.2.4 注意事项 2.3 栈 stack2.3.1 概述2.3.2 常用方法2.3.3 注意事项 2.4 队列 queue2.4.1 概述2.4.2 常用方法2.4.3 注意事项 2.5 优先…

【入坑系列】TiDB 强制索引在不同库下不生效问题

文章目录 背景SQL 优化情况线上SQL运行情况分析怀疑1:执行计划绑定问题?尝试:SHOW WARNINGS 查看警告探索 TiDB 的 USE_INDEX 写法Hint 不生效问题排查解决参考背景 项目中使用 TiDB 数据库,并对 SQL 进行优化了,添加了强制索引。 UAT 环境已经生效,但 PROD 环境强制索…

Redis(02)Win系统如何将Redis配置为开机自启的服务

一、引言 Redis 是一款高性能的键值对存储数据库&#xff0c;在众多项目中被广泛应用。在 Windows 环境下&#xff0c;为了让 Redis 能更稳定、便捷地运行&#xff0c;将其设置为系统服务并实现自动启动是很有必要的。这样一来&#xff0c;系统开机时 Redis 可自动加载&#xf…

apex新版貌似移除了amp从源码安装方式装的话会在from apex import amp时报错

问题&#xff1a; 安装完apex结果 from apex import amp会报错 解决方法&#xff1a; # apex git clone https://github.com/NVIDIA/apex cd apex # https://github.com/modelscope/ms-swift/issues/4176 git checkout e13873debc4699d39c6861074b9a3b2a02327f92 pip insta…

掌握 HTTP 请求:理解 cURL GET 语法

cURL 是一个强大的命令行工具&#xff0c;用于发送 HTTP 请求和与 Web 服务器交互。在 Web 开发和测试中&#xff0c;cURL 经常用于发送 GET 请求来获取服务器资源。本文将详细介绍 cURL GET 请求的语法和使用方法。 一、cURL 基本概念 cURL 是 "Client URL" 的缩写…

【AI学习】三、AI算法中的向量

在人工智能&#xff08;AI&#xff09;算法中&#xff0c;向量&#xff08;Vector&#xff09;是一种将现实世界中的数据&#xff08;如图像、文本、音频等&#xff09;转化为计算机可处理的数值型特征表示的工具。它是连接人类认知&#xff08;如语义、视觉特征&#xff09;与…

基于算法竞赛的c++编程(28)结构体的进阶应用

结构体的嵌套与复杂数据组织 在C中&#xff0c;结构体可以嵌套使用&#xff0c;形成更复杂的数据结构。例如&#xff0c;可以通过嵌套结构体描述多层级数据关系&#xff1a; struct Address {string city;string street;int zipCode; };struct Employee {string name;int id;…

leetcode题解450:删除BST中的结点!调整二叉树的结构最难!

一、题目内容 题目要求删除二叉搜索树&#xff08;BST&#xff09;中值为 key 的节点&#xff0c;并保证删除后二叉搜索树的性质不变。返回删除节点后的二叉搜索树的根节点的引用。一般来说&#xff0c;删除节点可分为两个步骤&#xff1a;首先找到需要删除的节点&#xff1b;如…

让 Kubernetes (K8s) 集群 使用 GPU

要让 Kubernetes (K8s) 集群 使用 GPU&#xff0c;并且节点是 KVM 虚拟化 出来的&#xff0c;需要确保以下几点&#xff1a; KVM 虚拟机透传 GPU&#xff08;PCIe Passthrough&#xff09; 宿主机和 K8s 节点正确安装 NVIDIA 驱动 K8s 集群安装 nvidia-device-plugin Pod 配…

Android第十七次面试总结(Java数据结构)

一、Java 集合体系核心架构与高频考点 1. 集合体系架构图 Java集合框架 ├─ Collection&#xff08;单列集合&#xff09; │ ├─ List&#xff08;有序、可重复&#xff09; │ │ ├─ ArrayList&#xff08;动态数组&#xff0c;随机访问快&#xff09; │ │ ├─…

Linux 删除登录痕迹

本文介绍相对彻底的删除 Linux 的登录痕迹&#xff0c;操作前确保已经可以拿到能提权ROOT令牌的系统管理权限。 当然&#xff0c;仍可以先查阅以下文章。 Linux 删除用户终端命令行操作记录-CSDN博客 1、清楚当前会话记录 history -c # 清空当前终端内存中的历史命令 2、永…

Lighttpd 配置选项介绍

根据提供的 Lighttpd 配置选项文档&#xff08;https://redmine.lighttpd.net/projects/lighttpd/wiki/Docs_ConfigurationOptions &#xff09;&#xff0c;以下是所有配置选项的详细解释、作用及适用场景&#xff0c;按模块分组说明&#xff1a; 以下是对 Lighttpd 配置选项 …

解决本地部署 SmolVLM2 大语言模型运行 flash-attn 报错

出现的问题 安装 flash-attn 会一直卡在 build 那一步或者运行报错 解决办法 是因为你安装的 flash-attn 版本没有对应上&#xff0c;所以报错&#xff0c;到 https://github.com/Dao-AILab/flash-attention/releases 下载对应版本&#xff0c;cu、torch、cp 的版本一定要对…

Python 训练营打卡 Day 40-训练和测试的规范写法

一.单通道图片的规范写法 以之前的MNIST数据集为例 import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader , Dataset # DataLoader 是 PyTorch 中用于加载数据的工具 from torchvision import datasets, transforms # t…

Java 枚举(Enum)的使用说明

在 Java 中&#xff0c;枚举&#xff08;Enum&#xff09;是一种特殊的数据类型&#xff0c;用于定义一组固定的命名常量。它比传统的常量&#xff08;如 public static final&#xff09;更安全、更灵活&#xff0c;且支持面向对象特性。以下是枚举的详细用法&#xff1a; 1. …