linux之shell脚本练习
以下脚本已经是在ubuntu下测试的
demo持续更新中。。。
1、for 循环测试,,,Ping 局域网
#!/bin/bashi=1
for i in {1..254}
do# 每隔0.3s Ping 一次,每次超时时间3s,Ping的结果直接废弃ping-w 3 -i 0.3 192.168.110.$i > /dev/nullif [ $? -eq 0 ];thenecho "192.168.120.$i is rechable"elseecho "192.168.120.$i is unrechable"fi#let i++
done
2、批量添加用户
#!/bin/bashuser=$(cat /opt/user.txt)for i in $user
doecho "$i"useradd "$i"echo $i:$i | chpasswd#echo "1234" | passwd --stdin $i
done
注意点:
- ubuntu 不支持--stdin,要用echo 和 chpasswd结合使用
- 在ubuntu 上要使用$(cat /opt/user.txt),而不是$`cat /opt/user.txt`, 否则通过for 循环遍历时,第一个数据老是给加上$,比如user.txt第一行的数据是user1,它会变成$user1,
有批量添加,就有批量删除
#!/bin/bashuser=$(cat /opt/user.txt)for i in $user
douserdel -f $i
done
3、将1-100中的奇数放入数组
#!/bin/bashfor((i=0;i<=100;i++))
doif [ $[i%2] -eq 1 ];thenarray[$[$[$i-1]/2]]=$ifi
done
#echo ${array[0]}
echo ${array[*]}
运行结果
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 95 97 99
知识点:
- $[] 是用来进行数学运算的,支持+、-、*、%、/。效果同$(())
- $[] 中括号里引用的变量可以不用加$符号,比如上面的 $[i%2]
- $[i%2]等同于$((i%2))
- array[*] 表示获取数组中的所有数据
4、创建任意数字及长度的数组,自定义元素
#!/bin/bashi=0while true
doread -p "input? yes or no:" operateif [ $operate = no ];thenbreakfiread -p "input the value:" valuearray[$i]=$valuelet i++
doneecho ${array[*]}
知识点:
- [ $doing = no ] 等价于[ $doing = "no" ] , = 是判断字符串的,对于纯字符串所以加不加引号都可
5、将数组中的数小于60的变成60,高于60的不操作
#!/bin/basharray=(61 62 63 50 59 64)
count=${#array[*]}echo before:${array[*]}
for((i=0;i<$count;i++))
do
if [ ${array[$i]} -lt 60 ] ; thenarray[$i]=60
fi
doneecho after:${array[*]}
知识点:
- 数组的定义中的元素之间用空格分开,不要用逗号(,)
- 数组的长度用 ${#array[*]} 或 ${#array[@]} 获取
- 数组元素的获取用 ${array[0]} , 赋值的时候不用加$ {}
6、判断数组中最大的数
#!/bin/bashmax=0
array=(1 2 5 3 7 9)
count=${#array[*]}for((i=0;i<$count;i++))
doif [ ${array[$i]} -gt $max ];thenmax=${array[$i]}fi
doneecho "the max num of array is ${max}"
知识点:
- 在取变量的时候需要加$,比如:$max, ${array[0]},再给变量赋值的时候不需要加$比如:max=1, array[0]=1
7、猜数字
#!/bin/bashseed=(0 1 2 3 4 5 6 7 8 9)
len=${#seed[*]}
random=$[RANDOM%$len]
guess=${seed[$random]}while :
doread -p "0-9? you guess which one? " doingif [ $doing -eq $guess ]; thenecho "bingo"exit 0elif [ $doing -gt $guess ]; thenecho "oops, too big"else echo "oops, too small"fidone
知识点
- $RANDOM 的范围是 [0, 32767]
- :空语句相当于true,即 while : 相当于 while true
8、删除数组中小于60的元素(unset)
#!/bin/bashnum=(58 59 60 61 62)i=0
for p in ${num[*]}
doif [ $p -lt 60 ]; thenunset num[$i]filet i++
doneecho the final result is ${num[*]}
exit 0
知识点:
- unset 为 shell 内建指令,用于删除定义的可读可写的shell变量(包括环境变量)和shell函数。不能对只读操作。
tt=1
echo $tt
unset tt
echo $tt
9、求1...100的和
#!/bin/bashsum=0
for i in {1..100}
dosum=$[$sum+$i]
doneecho the result is ${sum}
exit 0
10、求1...50的和(until)
#!/bin/bashsum=0
i=0until [ $i -gt 50 ]
do#sum=$[$sum+$i]let sum+=$ilet i++
doneecho the result is ${sum}
知识点:
- let 命令是 BASH 中用于计算的工具,用于执行一个或多个表达式,变量计算中不需要加上 $ 来表示变量。如果表达式中包含了空格或其他特殊字符,则必须引起来。
11、石头,剪刀,布
#!/bin/bashgame=(rock paper sissor)
random=$[$RANDOM%3]
scriptResult=${game[$random]}echo $scriptResultecho "choose your result:"
echo "1.rock"
echo "2.paper"
echo "3.sissor"read -p "choose 1, 2 or 3: " choicecase $choice in1)if [ $[$random+1] -eq 1 ]; thenecho "equal"elif [ $[$random+1] -eq 2 ]; thenecho "you lose"elseecho "you win"fi;;2)if [ $[$random+1] -eq 1 ]; thenecho "you win"elif [ $[$random+1] -eq 2 ]; thenecho "equal"elseecho "you lose"fi;;3)if [ $[$random+1] -eq 1 ]; thenecho "you lose"elif [ $[$random+1] -eq 2 ]; thenecho "you win"elseecho "equal"fi;;*)echo "wrong number";;esacexit 0
12、成绩计算(小于60 不及格 85以上优秀)
#!/bin/bashwhile :
doread -p "input score: " scoreif [ $score -le 100 ] && [ $score -gt 85 ]thenecho "great"elif [[ $score -lt 85 && $score -ge 60 ]]; thenecho "normal"elseecho "failed"fi
doneexit 0
知识点:
- [ $score -le 100 ] && [ $score -gt 85 ] 等价于 [[ $score -le 100 && $score -gt 85 ]] ,双中括号之间不要有空格,[[ ]] 是shell中的关键字,不是命令,单中括号[],是test命令
-
[[ ]] 不需要注意某些细枝末节,比[]功能强大
-
[[ ]] 支持逻辑运算
-
[[ ]] 支持正则表达式
-
[[]] 关键字
13、计算当前的内存使用百分比
#!/bin/bashmem_line=$(free -m | grep "Mem")
memory_total=$(echo $mem_line | awk '{print $2}')
memory_used=$(echo $mem_line | awk '{print $3}')echo "total memory: $memory_total MiB"
echo "used memory: $memory_used MiB"
#echo "usage rate: $[$memory_used/$memory_total * 100]%"
echo "usage rate:" $(echo $mem_line | awk '{printf("%0.2f%", $3 / $2 * 100)}')exit 0
知识点:
1、free -m 命令以MiB为单位打印
1 MiB = 1024KiB, 1MB=1000KiB
man free-m, --mebi Display the amount of memory in mebibytes.
total used free shared buff/cache available
Mem: 3876 1182 1518 3 1175 2428
Swap: 923 0 923
grep "Mem" 会将第二行(Mem开头的那行)抽取出来
2、awk 会进行文本处理, 利用printf函数处理小数
awk '{printf("%0.2f%", $3 / $2 * 100)}'
14、过滤出本机ether网卡的MAC地址
#!/bin/basheth=$(ifconfig | grep "ether" | awk '{print $2}')echo $ethexit 0
思路也简单,通过ifconfig 获取ether所在行,通过awk获取对应行的第二个参数$2
ens37: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet6 fe80::5e0a:f1cf:cbf8:4c2d prefixlen 64 scopeid 0x20<link>
ether 00:0c:29:f6:b6:99 txqueuelen 1000 (Ethernet)
RX packets 87 bytes 10378 (10.3 KB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 3992 bytes 720667 (720.6 KB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
inet6 ::1 prefixlen 128 scopeid 0x10<host>
loop txqueuelen 1000 (Local Loopback)
RX packets 68614 bytes 4911600 (4.9 MB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 68614 bytes 4911600 (4.9 MB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
15、
linux 程序设计 第四版 shell 脚本
已调试,大致没问题,想学习的复制拿去
#!/bin/shmenu_choice=""
current_cd=""
title_file="title.cdb"
tracks_file="tracks.cdb"
temp_file=/tmp/cdb.$$
trap 'rm -f $temp_file' EXITget_return() {echo "Please return \c"read xreturn 0
}get_confirm() {echo -e "Are you sure? \c"while truedoread xcase "$x" iny | yes|Y|Yes|YES) return 0;;n | no|N|No|NO) echoecho "Cancelled"return 1;;*) echo "Please enter yes or no";;esacdone}set_menu_choice() {clearecho "Options : -"echoecho " a) Add new CD"echo " f) Find CD"echo " c) Cont the CDs and tracks in the catalog"if [ "$cdcatnum" != "" ]; thenecho " l) List track on $cdtitle"echo " r) Remove $cdtitle"echo " u) Update track information for $cdtitle"fiecho " q) Quit"echo echo "Please enter choice then press return \c"read menu_choicereturn
}insert_title() {echo $* >> $title_filereturn
}insert_track() {echo $* >> $tracks_filereturn
}add_record_tracks() {echo "Enter track information for this CD"echo "When no more tracks enter q"cdtrack=1cdtitle=""while [ "$cdtitle" != "q" ] doecho "Track $cdtrack, track title? \c"read tmpcdtitle=${tmp%%, *}echo ${tmp}======echo ${cdtitle}-------if [ "$tmp" != "$cdtitle" ]; thenecho "Sorry, no commas allowed"continuefiif [ -n "$cdtitle" ]; thenecho enterecho ${cdtitle}-------if [ "${cdtitle}" != "q" ]; thenecho enter1insert_track $cdcatnum, $cdtrack, $cdtitlefielsecdtrack=$((cdtrack-1))ficdtrack=$((cdtrack+1))done
}add_records() {echo "Enter catalog name \c"read tmp;cdcatnum=${tmp%%, *}echo "Enter title \c"read tmpcdtitle=${tmp%%, *}echo "Enter type \c"read tmpcdtype=${tmp%%, *}echo "Enter artist/composer \c"read tmpcdac=${tmp%%, *}echo About to add new entryecho "$cdcatnum $cdtitle $cdtype $cdac"if get_confirm; theninsert_title $cdcatnum, $cdtitle, $cdtype, $cdacadd_record_trackselseremove_recordsfireturn
}find_cd() {if [ "$1" = "n" ] ; then asklist=nelseasklist=yficdcatnu=""echo -e "Enter a string to search for in the CD titles \c"read searchstrif [ "$searchstr" = "" ] ; thenreturn 0figrep "$searchstr" $title_file > $temp_fileset $(wc -l $temp_file)linesfound=$1case "$linesfound" in0) echo "Sorry, nothing found"get_returnreturn 0;;1) ;;2) echo "Sorry, not unique"echo "Found the following"cat $temp_fileget_returnreturn 0esacIFS=","read cdcatnum cdtitle cdtype cdac < $temp_fileIFS=" "if [ -z "$cdcatnum" ]; thenecho "Sorry, cound not extract catalog field from $temp_file"get_returnreturn 0fiechoecho Catalog num: $cdcatnumecho Title: $cdtitleecho TYPe: $cdtypeecho Artist: $cdacechoget_returnif [ "$asklist" = "y" ]; thenecho -e "View tracks for this CD? \c"if [ "$x" = "y" ]; thenecholist_tracksechofi fireturn 1
}update_cd() {if [ -z "$cdcatnum" ]; thenecho "You must select a CD first"find_cd nfiif [ -n "$cdcatnum" ]; then echo "Current tracks are: -"list_tracksechoecho "This will re_enter the tracks for $cdtitle"get_confirm && {grep -v "^${cdcatnum}," $tracks_file > $temp_filemv $temp_file $tracks_fileechoadd_record_tracks}fireturn
}count_cds() {set $(wc -l $title_file)num_titles=$1set $(wc -l $tracks_file)num_tracks=$1echo found $num_title CDs, with a total of $num_tracks tracksget_returnreturn
}remove_records() {if [ -z "$cdcatnum" ]; thenecho You must select a CD firstfind_cd nfiif [ -n "$cdcatnum" ]; thenecho "You are about to delete $cdtitle"get_confirm && {grep -v "^${cdcatnum}," $title_file > $temp_filemv $temp_file $title_filegrep -v "^${cdcatnum}," $tracks_file > $temp_filemv $temp_file $tracks_filecdcatnum=""echo Entry removed}get_returnfireturn
}list_tracks() {if [ "$cdcatnum" = "" ]; thenecho no CD selected yetreturnelsegrep "^${cdcatnum}," $tracks_file > $temp_filenum_tracks=$(wc -l $temp_file)if [ "$num_tracks" = "0" ]; thenecho no tracks found for $cdtitleelse {echoecho "$cdtitle :-"echo cut -f 2- -d, $temp_file} | ${PAGER:-more}fifiget_returnreturn
}rm -f $temp_fileif [ ! -f $title_file ];thentouch $title_file
fiif [ ! -f $title_file ]; thentouch $tracks_file
ficlear
echo
echo
echo "Mini CD manager"
sleep 1quit=n
while [ "$quit" != "y" ];
doset_menu_choicecase "$menu_choice" ina) add_records;;r) remove_records;;f) find_cd y;;u) update_cd;;c) count_cds;;l) list_tracks;;b) echomore $title_fileechoget_return;; q|Q) quit=y;;*) echo "Sorry, choice not recognized";;esac
donerm -f $temp_file
echo "Finished"
exit 0
相关文章:
linux之shell脚本练习
以下脚本已经是在ubuntu下测试的 demo持续更新中。。。 1、for 循环测试,,,Ping 局域网 #!/bin/bashi1 for i in {1..254} do# 每隔0.3s Ping 一次,每次超时时间3s,Ping的结果直接废弃ping-w 3 -i 0.3 192.168.110.$i…...
CSS阶详细解析一
CSS进阶 目标:掌握复合选择器作用和写法;使用background属性添加背景效果 01-复合选择器 定义:由两个或多个基础选择器,通过不同的方式组合而成。 作用:更准确、更高效的选择目标元素(标签)。…...
osWorkflow-1——osWorkflow官方例子部署启动运行(版本:OSWorkflow-2.8.0)
osWorkflow-1——osWorkflow官方例子部署启动运行(版本:OSWorkflow-2.8.0) 1. 前言——准备工作1.1 下载相关资料1.2 安装翻译插件 2. 开始搞项目2.1 解压 .zip文件2.2 简单小测(war包放入tomcat)2.3 导入项目到 IDE、…...
Stm32_标准库_13_串口蓝牙模块_手机与蓝牙模块通信
代码: #include "stm32f10x.h" // Device header #include "Delay.h" #include "OLED.h" #include "Serial.h"char News[100] "";uint8_t flag 1;void Get_Hc05News(char *a){uint32_t i 0…...
Unity中用序列化和反序列化来保存游戏进度
[System.Serializable]标记类 序列化 [System.Serializable]是一个C#语言中的属性,用于标记类,表示该类的实例可以被序列化和反序列化。序列化是指将对象转换为字节流的过程,以便可以将其保存到文件、数据库或通过网络传输。反序列化则是将字…...
Junit 单元测试之错误和异常处理
错误和异常处理是测试中非常重要的部分。假设我们有一个服务,该服务从数据库中获取用户。现在,我们要考虑的错误场景是:数据库连接断开。 整体代码示例 首先,为了简化,我们让服务层就是简单的类,然后使用I…...
LockSupport-park和unpark编码实战
package com.nanjing.gulimall.zhouyimo.test;import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.LockSupport;/*** author zhou* version 1.0* date 2023/10/16 9:11 下午*/ public class LockSupportDemo {public static void main(String[] args) {…...
js深拷贝与浅拷贝
1.浅拷贝概念 浅拷贝是其属性与拷贝源对象的属性共享相同引用,当你更改源或副本时,也可能(可能说的是只针对引用数据类型)导致其他对象也发生更改。 特性: 会新创建一个对象,即objobj2返回fasle…...
Docker-harbor私有仓库部署与管理
搭建本地私有仓库 #首先下载 registry 镜像 docker pull registry #在 daemon.json 文件中添加私有镜像仓库地址 vim /etc/docker/daemon.json { "insecure-registries": ["20.0.0.50:5000"], #添加,注意用逗号结…...
ArcGIS笔记8_测量得到的距离单位不是米?一经度一纬度换算为多少米?
本文目录 前言Step 1 遇到测量结果以度为单位的情况Step 2 简单的笨办法转换为以米为单位Step 3 拓展:一经度一纬度换算为多少米 前言 有时我们会遇到这种情况,想在ArcGIS中使用测量工具测量一下某一段距离,但显示的测量结果却是某某度&…...
SpringBoot入门详解
目录 因何而生的SpringBoot 单体架构的捉襟见肘 SpringBoot的优点 快速入门 高曝光率的Annotation SpringBoot的工作机制 了解SpringBootApplication SpringBootConfiguration EnableAutoConfiguration 自动配置的幕后英雄:SpringFactoriesLoader Compon…...
数据分析案例-基于snownlp模型的MatePad11产品用户评论情感分析(文末送书)
🤵♂️ 个人主页:艾派森的个人主页 ✍🏻作者简介:Python学习者 🐋 希望大家多多支持,我们一起进步!😄 如果文章对你有帮助的话, 欢迎评论 💬点赞Ǵ…...
Leetcode刷题解析——904. 水果成篮
1. 题目链接:904. 水果成篮 2. 题目描述: 你正在探访一家农场,农场从左到右种植了一排果树。这些树用一个整数数组 fruits 表示,其中 fruits[i] 是第 i 棵树上的水果 种类 。 你想要尽可能多地收集水果。然而,农场的主…...
Spring Boot RESTful API
学习到接口部分了,记录一下 关于restful api感觉这篇文章讲的十分详细且通俗易懂一文搞懂什么是RESTful API - 知乎 (zhihu.com) Spring Boot 提供的 spring-boot-starter-web 组件完全支持开发 RESTful API ,提供了 GetMapping:处理get请求…...
k8s day04
昨日内容回顾: - configMap ---> cm 应用场景: 主要用于配置文件的持久化。 - secret 应用场景: 存储敏感数据,并非加密数据。 - pod探针(probe): - livenessProbe: 健康检查探针&#x…...
ESP32-IPS彩屏ST7789-Arduino-简单驱动
目的: 使ESP32能够驱动点亮ST7789显示屏 前提条件: ESP32 ST7789 (240 x240,IPS) 杜邦线 Arduino 过程: 0x00--接线 0x01--驱动: 彩屏驱动库 针对不同的彩屏驱动芯片,常用的 Arduino…...
高效工具类软件使用
高效工具类软件使用 目录概述需求: 设计思路实现思路分析1.Leanote2.Obsidian 的使用 参考资料和推荐阅读 Survive by day and develop by night. talk for import biz , show your perfect code,full busy,skip hardness,make a better result,wait for…...
批处理文件(.bat)中,dir与tree命令的效果
目录 dir命令 用法 操作 效果 dir /? dir dir D:\111\111_3 dir D:\111 *.mp4 dir D:\111 /ad dir D:\111 /ar dir D:\111 /s dir D:\111\111_3 >1bat.txt dir D:\111 >>1bat.txt tree命令 用法 操作 效果 tree /? tree tree D:\111\111_3 tree…...
STM32 ---- 再次学习STM32F103C8T6/STM32F409IGT6
目录 一、环境搭建及介绍 关于STM32基础介绍 新建工程 外设案例 LED流水灯 蜂鸣器 上拉电阻和下拉电阻知识 电压比较器 c语言基础知识 类型、结构体、枚举 类型int8_t int16_t int32_t 宏替换 #define 和typedef用法 结构体两种填充方法 和 命名规则 枚举用法 常用…...
UE4 EQS环境查询 学习笔记
EQS环境查询对应Actor的范围 EQS环境查询查询对应的类 查询到即有一个蓝色的球在Actor上,里面有位置信息等等 在行为树运行EQS,按键(‘)可以看到Player的位置已经被标记 运行对应的EQS在这里放如EQS就可以了 Generated Point&…...
Chapter03-Authentication vulnerabilities
文章目录 1. 身份验证简介1.1 What is authentication1.2 difference between authentication and authorization1.3 身份验证机制失效的原因1.4 身份验证机制失效的影响 2. 基于登录功能的漏洞2.1 密码爆破2.2 用户名枚举2.3 有缺陷的暴力破解防护2.3.1 如果用户登录尝试失败次…...
conda相比python好处
Conda 作为 Python 的环境和包管理工具,相比原生 Python 生态(如 pip 虚拟环境)有许多独特优势,尤其在多项目管理、依赖处理和跨平台兼容性等方面表现更优。以下是 Conda 的核心好处: 一、一站式环境管理:…...
1.3 VSCode安装与环境配置
进入网址Visual Studio Code - Code Editing. Redefined下载.deb文件,然后打开终端,进入下载文件夹,键入命令 sudo dpkg -i code_1.100.3-1748872405_amd64.deb 在终端键入命令code即启动vscode 需要安装插件列表 1.Chinese简化 2.ros …...
什么?连接服务器也能可视化显示界面?:基于X11 Forwarding + CentOS + MobaXterm实战指南
文章目录 什么是X11?环境准备实战步骤1️⃣ 服务器端配置(CentOS)2️⃣ 客户端配置(MobaXterm)3️⃣ 验证X11 Forwarding4️⃣ 运行自定义GUI程序(Python示例)5️⃣ 成功效果加入系统变量…...
比较数据迁移后MySQL数据库和OceanBase数据仓库中的表
设计一个MySQL数据库和OceanBase数据仓库的表数据比较的详细程序流程,两张表是相同的结构,都有整型主键id字段,需要每次从数据库分批取得2000条数据,用于比较,比较操作的同时可以再取2000条数据,等上一次比较完成之后,开始比较,直到比较完所有的数据。比较操作需要比较…...
6个月Python学习计划 Day 16 - 面向对象编程(OOP)基础
第三周 Day 3 🎯 今日目标 理解类(class)和对象(object)的关系学会定义类的属性、方法和构造函数(init)掌握对象的创建与使用初识封装、继承和多态的基本概念(预告) &a…...
Python网页自动化Selenium中文文档
1. 安装 1.1. 安装 Selenium Python bindings 提供了一个简单的API,让你使用Selenium WebDriver来编写功能/校验测试。 通过Selenium Python的API,你可以非常直观的使用Selenium WebDriver的所有功能。 Selenium Python bindings 使用非常简洁方便的A…...
