基于centos7学习总结 -- shell脚本

2023-05-16

shell 脚本必须要以"#!/bin.bash"开头。
脚本建议内容:

  • 脚本的功能
  • 脚本的版本信息
  • 脚本的作者与联系方式
  • 脚本的版权声明方式
  • 脚本的History
  • 脚本内特殊的命令,使用【绝对路径】的方式来执行
  • 脚本运行时需要的环境变量预先声明预设置
    示例:
    在这里插入图片描述
#!/bin/bash
# Program:
#       This program shows "create 2 day age,1 day age and today filename"
#
#Creat:
#       2021/11/11 
#
#Hirstory:
#
#
#Creater/Contact:
#       Mr_Chang        1135130670@qq.com
#
read -p "Please input filename" userfile
userfilename=${userfile:-"filename"}
date1=$(date --date='2 days ago' +%y-%m-%d)
date2=$(date --date='1 days ago' +%y-%m-%d)
date3=$(date  +%y-%m-%d)

filename1=${userfilename}-${date1}
filename2=${userfilename}-${date2}
filename3=${userfilename}-${date3}

touch "${filename1}"
touch "${filename2}"
touch "${filename3}"

进行数值运算时需用$(())引起来计算。
$((计算式))

#!/bin/bash
# Program:
#       This program shows "multiplay"
#
#Creat:
#       2021/11/11 
#
#Hirstory:
#
#
#Creater/Contact:
#       Mr_Chang        1135130670@qq.com
#

read -p "file number:" fNum
read -p "secound number:" sNum

sum=$((${fNum}+${sNum}))

echo "total -->  ${sum}"

脚本执行方式的差异(source、sh script 、./script)

source或./script:在当前环境下的shell执行,脚本运行结束后,脚本内的变量在当前shell中依然存在。

sh script:另打开一个子bash shell,运行完后子shell内的变量随着进程结束而消失,要想保留则需export来声明成环境变量。

test 判别式

在这里插入图片描述

test可以使用 [ ] 来替换

[-z "${HOME}"] ; echo $?

使用 [ ] 时特别注意:

  1. 中括号内每个组件都需要使用空格来分隔开
  2. 中括号内的每个变量最好都使用双引号引起来
  3. 中括号内的常数最好以单或双引号括起来

shell脚本的默认变量

/tmp/shell/scriptname  opt1  opt2  opt3  opt4 
       $0             $1    $2    $3    $4

$0:表示脚本名
$1:表示第一个变量
$2:表示第二个变量
.
.
.
$#:表示参数总个数
$@:表示【 “$1” “$2” “$3” “$4” 】之意,每个变数是独立的(用双引号括起来);
$*:表示【 “$1c$2c$3c$4” 】,其中 c 为分隔符,默认为空格, 前面代表【 “$1 $2 $3 $4” 】之意。

shift 造成号码偏移

#!/bin/bash
# Program:
#       This program shows shell shift functionasily
#
#Creat:
#       2021/11/11 
#
#Hirstory:
#
#
#Creater/Contact:
#       Mr_Chang        1135130670@qq.com
#

echo "shell variables count: $#"
echo "show shell variable : '$@'"

echo "used shift"
shift
echo "shell variables count: $#"
echo "show shell variable : '$@'"

echo "used shift 3"
shift 3
echo "shell variables count: $#"
echo "show shell variable : '$@'"

在这里插入图片描述

条件判别式

if…then

if [ 条件判别式 ]; then
条件成立时可以进入执行的代码
fi

#!/bin/bash
# Program:
#	This program shows if else fi. know netstat
#
#Creat:
#	2021/11/11 
#
#Hirstory:
#
#
#Creater/Contact:
#	Mr_Chang	1135130670@qq.com
#
#

testfile="/data/shell_script/netstat_data"
#在这里需要注意下,${testfile} 是取出变量值,然后 netstat -tnul 执行结果重定向到 变量值(/data/shell_script/netstat_data)文件内。
netstat -tnul > ${testfile}

testing=$( grep ':80' ${testfile})

if [ "${testing}" != "" ];then

	echo "WWW is running in your system."

fi

testing=$( grep ':22' ${testfile})
if [ "${testing}" != "" ];then

        echo "SSH is running in your system."

fi

testing=$( grep ':21' ${testfile})
if [ "${testing}" != "" ];then

        echo "ftp is running in your system."

fi


testing=$( grep ':25' ${testfile})
if [ "${testing}" != "" ];then

        echo "Mail is running in your system."

fi

在此再强调下," [ ] "符号和变量、常量或比较符之间一定要用空格隔开,否则会引起语法错误。

case…esac

语法:

case $变量名 in
	"第一个变量的内容" )
		程序段
		;;
	"第二个变量内容")
		程序段
		;;
	* )
		程序段
		;;

“*” 表示如果没有匹配到变量内容,默认执行 “*” 下的程序段

#!/bin/bash
# Program:
#       This program shows case in operation
#
#Creat:
#       2021/11/11 
#
#Hirstory:
#
#
#Creater/Contact:
#       Mr_Chang        1135130670@qq.com
#

case ${1} in

        "one" )
                echo "You input is One."
                ;;
        "tow" )
                echo "You input is Two."
                ;;
        "three" )
                echo "You input is Three"
                ;;
        * )
                echo "Please input ${0} {one | two | three }"
                ;;

esac

在这里插入图片描述

shell 中的 function

语法:

function 函数名() {
    程序段
{
#!/bin/bash
# Program:
#	This program shows function option
#
#Creat:
#	2021/11/11 
#
#Hirstory:
#
#
#Creater/Contact:
#	Mr_Chang	1135130670@qq.com
#

function printit(){
	echo -n "You input is "
}

case ${1} in

	"one" )
		printit;echo ${1} | tr 'a-z' 'A-Z'
		;;
	"two" )
		printit;echo ${1} | tr 'a-z' 'A-Z'
		;;
	"three" )
		printit;echo ${1} | tr 'a-z' 'A-Z'
		;;
	* )
		echo "Please input ${0} {one | two | three }"
		;;

esac 

在这里插入图片描述

在function中也是可以传递参数的。
使用 【$1】代表第一个参数,【$2】表示第二个参数

#!/bin/bash
# Program:
#       This program shows function parameter option
#
#Creat:
#       2021/11/11 
#
#Hirstory:
#
#
#Creater/Contact:
#       Mr_Chang        1135130670@qq.com
#

function printit(){
        echo "Your choise is  ${1}"

}

case ${1} in

        "one" )
                printit 1
                ;;
        "two" )
                printit 2
                ;;
        "three" )
                printit 3
                ;;
        * )
                echo "Please input ${0} {one | two | three }"
                ;;

esac

-------------------------------------------------------------------------------

[root@localhost shell_script]# sh function_parm.sh one
Your choise is  1
[root@localhost shell_script]# sh function_parm.sh two
Your choise is  2
[root@localhost shell_script]# sh function_parm.sh three
Your choise is  3
[root@localhost shell_script]# sh function_parm.sh error
Please input function_parm.sh {one | two | three }

当 【 函数名(实参)】 传递给函数值是,函数第一个接收的变量为【$1】,第二个接收的变量为【$2】

循环 while do done 、until do done 和 for do done

while do done 和 until do done 称为不定时循环

while do done

语法:

while [condition] 
do
	程序段
done

当判别式成立时才会进入循环执行循环体程序段

until do done

语法:

until [condition]
do
	程序段
done

当判别式为成立时结束循环

#!/bin/bash
# Program:
#       This program shows loop
#
#Creat:
#       2021/11/11 
#
#Hirstory:
#
#
#Creater/Contact:
#       Mr_Chang        1135130670@qq.com
#

while [ "${yn}" != "yes" -a "${yn}" != "YES" ]
do
        read -p "Pl;ease input yes/YES to stop this program :" yn
done

echo "You input the correct answer!"


--------------------------------------------------------------
[root@localhost shell_script]# sh loop_unit_which.sh 
Pl;ease input yes/YES to stop this program :y^Ho
Pl;ease input yes/YES to stop this program :o
Pl;ease input yes/YES to stop this program :y
Pl;ease input yes/YES to stop this program :yes
You input the correct answer!
[root@localhost shell_script]# 
                   

for do done

语法1:

for var in list
do
	程序段
done

语法1有点类似类似于java的增强for循环,循环依次拿出集合中的值。
在此,循环一次从list中拿出一个值赋给变量【var】

语法2:

for((起始值; 判别式; 赋值运算))
do
	程序段
done

语法2是针对固定循环次数的循环,指定循环多少次的意思。

例题1:随机选出今天去哪家店吃午餐

#!/bin/bash
# Program:
#       This program shows loop for which choise one shops
#
#Creat:
#       2021/11/11 
#
#Hirstory:
#
#
#Creater/Contact:
#       Mr_Chang        1135130670@qq.com
#

eat[1]="賣噹噹漢堡"       # 寫下你所收集到的店家!
eat[2]="肯爺爺炸雞"
eat[3]="彩虹日式便當"
eat[4]="越油越好吃大雅"
eat[5]="想不出吃啥學餐"
eat[6]="太師父便當"
eat[7]="池上便當"
eat[8]="懷念火車便當"
eat[9]="一起吃泡麵"

index=9

randoms=$(( ${RANDOM}*${index}/32767 +1))

echo "Today we choice ${eat[${randoms}]}"



--------------------------------------------------------------------------

[root@localhost shell_script]# sh loop_for_random_choice.sh 
Today we choice 池上便當
[root@localhost shell_script]# sh loop_for_random_choice.sh 
Today we choice 懷念火車便當
[root@localhost shell_script]# sh loop_for_random_choice.sh 
Today we choice 想不出吃啥學餐
[root@localhost shell_script]# sh loop_for_random_choice.sh 
Today we choice 太師父便當
[root@localhost shell_script]# sh loop_for_random_choice.sh 
Today we choice 池上便當
[root@localhost shell_script]# sh loop_for_random_choice.sh 
Today we choice 越油越好吃大雅

例题2:随机选出今天三家店

#!/bin/bash
# Program:
#       This program shows loop for while choise three shops
#
#Creat:
#       2021/11/11 
#
#Hirstory:
#
#
#Creater/Contact:
#       Mr_Chang        1135130670@qq.com
#

eat[1]="賣噹噹漢堡"       # 寫下你所收集到的店家!
eat[2]="肯爺爺炸雞"
eat[3]="彩虹日式便當"
eat[4]="越油越好吃大雅"
eat[5]="想不出吃啥學餐"
eat[6]="太師父便當"
eat[7]="池上便當"
eat[8]="懷念火車便當"
eat[9]="一起吃泡麵"

index=9
eated=0

while [ "${eated}" -lt 3 ] 
do
        mycheck=0
        check=$(( ${RANDOM}*${index}/32767 +1))
        if [ "${eated}" -ge 1 ]; then
                for i in $(seq 1 ${eated})
                do
                        if [ "${eatedcon[$i]}" == ${check} ];then
                                mycheck=1
                        fi
                done
        fi
done
--------------------------------------------------------------------------
[root@localhost shell_script]# sh loop_for_random_choice1.sh 
choice 肯爺爺炸雞
choice 太師父便當
choice 彩虹日式便當
[root@localhost shell_script]# sh loop_for_random_choice1.sh 
choice 池上便當
choice 越油越好吃大雅
choice 想不出吃啥學餐
[root@localhost shell_script]# sh loop_for_random_choice1.sh 
choice 肯爺爺炸雞
choice 一起吃泡麵
choice 太師父便當

shell脚本的调试

sh [-nvx] script.sh
	-n	仅进行语法检测,不执行脚本
	-v	在执行前,先查看脚本内容
	-x	将使用到的脚本内容显示到屏幕上,类似于debug

为了简单说明各参数的租用,这里使用相对较为简单例子说明

#!/bin/bash
# Program:
#       This program shows "input you firstname and lastname. Program shows your full name" in you screen
#
#Creat:
#       2021/11/11 17:18
#
#Hirstory:
#
#
#Creater/Contact:
#       Mr_Chang        1135130670@qq.com
#
read -p "Please input your fistname:" firstname
read -p "Please inout your lastname" lastname
echo "Your name is ${firstname}${lastname}"
exit 0
      

在这里插入图片描述

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

基于centos7学习总结 -- shell脚本 的相关文章

  • Python 3.7 安装完成后import ssl失败解决方法

    提示找不到SSL模块 python安装完毕后 xff0c 提示找不到ssl模块 xff1a root 64 localhost python2 7 5 Python 2 7 5 default Jun 3 2013 11 08 43 GCC
  • activemq的安装和使用【2】activemq的queue模式

    activemq共有两种模式 xff0c 一是点对点 xff0c 一是发布和订阅 xff0c 不管是哪种方式 xff0c 都包含两个角色 xff0c 一是消息的生产者 xff0c 一是消息的消费者 点对点是消息只能被一个消费者收到 xff0
  • Nacos源码分析

    Nacos源码分析 1 下载Nacos源码并运行 要研究Nacos源码自然不能用打包好的Nacos服务端jar包来运行 xff0c 需要下载源码自己编译来运行 1 1 下载Nacos源码 Nacos的GitHub地址 xff1a https
  • Sentinel源码分析

    Sentinel源码分析 1 Sentinel的基本概念 Sentinel实现限流 隔离 降级 熔断等功能 xff0c 本质要做的就是两件事情 xff1a 统计数据 xff1a 统计某个资源的访问数据 xff08 QPS RT等信息 xff
  • Nginx 基础使用、配置文件详解、Keepalived高可用

    Nginx 基础使用 安装 span class token comment 解压nginx压缩包 xff0c 压缩包自行下载 span tar zxvf nginx 1 span class token punctuation span
  • 阿里巴巴Java开发手册中的DO、DTO、BO、AO、VO、POJO定义

    常用文件夹分层 xff1a pojo vo xff08 与前端交互的所有对象 xff0c 包括接参和返回 xff09 query xff08 查询的筛选条件 xff0c 前端传参和后端内部传参通用 xff09 entity xff08 数据
  • 分布式锁笔记

    分布式锁笔记 分布式锁1 传统锁回顾1 1 从减库存聊起1 2 环境准备1 3 简单实现减库存1 4 演示超卖现象1 5 jvm锁问题演示1 5 1 添加jvm锁1 5 2 原理 1 6 多服务问题1 6 1 安装配置nginx1 6 2
  • 分布式锁总结

    乐观锁 在select的时候不会加锁 xff0c 是基于程序实现的 xff0c 所以不会存在死锁的情况 适用于读多写少的场景 xff08 写的并发量相对不高 xff09 xff0c 可以提高系统的吞吐量 因为如果写多的话 xff0c 乐观锁
  • Xstart远程连接Linux图形用户界面

    目标 xff1a 在自己的Windows桌面打开Linux的firefox浏览器 工具 xff1a Windows Xmanager的Xstart工具 Linux xterm firefox 说明 xff1a 使用Xstart远程连接Lin
  • 微信内置小程序在线客服功能

    在小程序中加入客服消息按钮 小程序接入微信 客服消息 功能模块 xff0c 开发者只需要调用按钮 xff0c 触发微信的客服消息功能即可 xff0c 不需要自行在小程序中实现 加入客服消息按钮有两个方法 xff0c 大家可以根据自己的实际需
  • Java实例化泛型

    public D newUsr D newUsr try 通过反射获取model的真实类型 ParameterizedType pt 61 ParameterizedType this getClass getGenericSupercla
  • Windows桌面下面任务栏无法点击(卡住)的解决办法

    Windows桌面下面任务栏无法点击 卡住 的解决办法 大家再使用Windows的时候 xff0c 有时候会碰到桌面卡住无法点击下面的任何图标的现象 xff0c 若不知道如何解决 xff0c 可能就开始重启电脑了 xff0c 其实不必要 x
  • 剑指offer03

    数组中的重复数字 题目 在一个长度为 n 的数组 nums 里的所有数字都在 0 xff5e n 1 的范围内 数组中某些数字是重复的 xff0c 但不知道有几个数字重复了 xff0c 也不知道每个数字重复了几次 请找出数组中任意一个重复的
  • 如何pycharm与jupyter lab/notebook结合使用

    如何pycharm与jupyter lab notebook结合使用 原因效果教程 原因 jupyter lab的自动补全并不好用 xff0c 使用了kite后总是存在卡顿的现象 xff0c 正好在pycharm中支持jupyter lab
  • 【杭电100题】2073 无限的路

    题目链接 xff1a http acm hdu edu cn showproblem php pid 61 2073 xff08 c语言的double类型printf lf 显示0 00000问题 xff09 xff1a https blo
  • 【杭电100题】2094 产生冠军

    原题 xff1a http acm hdu edu cn showproblem php pid 61 2094 最近很喜欢用map 把成功者 失败者都存起来 然后在成功者里把曾经失败的划掉 最后成功者里如果只剩一个人 xff0c 冠军产生
  • 逆变电路

    逆变的概念 与整流相对应 xff0c 直流电 变成 交流电 交流侧接电网 xff0c 为 有源逆变 交流侧接负载 xff0c 为 无源逆变 xff0c 本章主要讲述无源逆变 逆变与变频 变频电路 xff1a 分为 交交变频 和 交直交变频
  • 博客搭建教程1-Archlinux环境配置

    文章目录 1 前言2 archlinux镜像下载3 archlinux安装 1 前言 这个教程主要讲解linux环境下博客的搭建 xff0c 这里的linux系统选择archlinux xff0c 博客的框架基于hexo框架 参考博客 xf
  • 如何在git bash中启用复制粘贴快捷键

    方法一 xff1a 1 鼠标右键点击左上角 xff0c 选择属性 xff08 如果是英文就选择properties xff09 xff1a 2 在选项中勾选相应选项 xff1a 然后就完事了 方法二 xff1a 从其他地方复制一段文本 2
  • 栈,队列(纸牌游戏,小猫钓鱼)

    文章目录 队列 xff1a FIFO实现顺序队列 xff1a 1 顺序循环队基本操作2 链队 栈1 顺序栈栈的元素初始化操作入栈操作判断顺序栈是否为空栈的长度出栈清空一个栈销毁顺序栈 2 链式栈 应用栈1 xff1a 判断回文字符串栈与队列

随机推荐

  • SELinux

    domain https www cnblogs com ly565911158 p 3622942 html coredomain https www cnblogs com liwugang p 12433028 html xff08
  • 电脑任务栏无法点击

    解决方法 1 启动任务管理器 xff08 Ctrl 43 alt 43 找到windows 资源管理器重新启动 xff09 2 win10 更新后右下方有个天气资讯的推送点击全部选择关闭 xff0c 在任务栏上也点击取消
  • 如何快速获取网页源码(直接把网站的 js css html 扒下来的)

    如何快速获取网页源码 xff1f 我们在学习和研究的时候 或者看到非常酷炫的页面效果 xff0c 需要网站的源代码进行借鉴 xff0c 但每次需要下载网站源代码 xff0c 我们都需要找到一个 xff0c 下载一个 xff0c 每次只能下载
  • 人工智能大作业——人脸识别系统(最终)

    写在前面 时间过得飞快 xff0c 时间已经距离我发第一篇文章过去2年多了 xff0c 也不再从事代码工作 xff0c 偶然间上到csdn翻看文章经过 xff0c 看到还是有些人关注人脸识别系统的后续的 xff0c 我猜大概率是学弟学妹们正
  • JAVA json 三种格式

    json三种格式 span class token class name JSONObject span jsonParam span class token operator 61 span span class token keywor
  • java.lang.NumberFormatException: For input string: ""解决方案

    引起异常的主要原因如下 xff1a 1 传参字段和映射字段不一致2 传参类型和映射类型不一致3 时间类型转换时间戳长度不一致4 参数长度和数据库不一致 Service 层代码 span class token keyword public
  • 个性化命令提示符CMD,不止简单地美化,Dos命令让你的命令提示符cmd花里胡哨

    自重温了下注册表知道了autorun子项后 我把cmd重新设计了一遍 先上图 win10系统 cmd版本为10 0 17763 1 原理 添加注册表命令行的自启动项 使启动cmd时会自动运行项的命令值 打开注册表 win R 输入reged
  • Pandas入门第二章之数据的读取

    本节主要介绍pandas经常读取的两种数据格式 xff0c 其分别是CSV和JSON本节使用两个数据集分别是2019腾讯算法大赛和中国AI创新创业大赛的数据集 没有标签的原始数据的格式 带标题的数据格式 本节在介绍pandas读取CSV文件
  • 使用Javascript 创建枚举类型(enum)

    使用Javascript 创建枚举类型 xff08 enum xff09 1 枚举类型的定义 是指将变量的值一一列出来 变量的值只限于列举出来的值的范围内 2 typescript中的枚举类型 span class token keywor
  • 一个七年Java女程序员的年终总结,写给过去一年的自己

    简单先说一下 xff0c 坐标杭州 xff0c 14届本科毕业 xff0c 算上年前在阿里巴巴B2B事业部的面试 xff0c 一共有面试了有6家公司 xff08 因为不想请假 xff0c 因此只是每个晚上去其他公司面试 xff0c 所以面试
  • HTML初识

    文章目录 思维导图HTML标签浏览器内核Web标准骨架标签VScode的使用网页开发工具解释标签图像标签注意点路径视频格式 xff08 后续会补充 xff09 链接 思维导图HTML标签 xff08 表示后面有相应解释 xff09 浏览器内
  • 建造者模式

    建造者模式 建造者模式也属于创建型模式 xff0c 它提供了一种创建对象的最佳方式 定义 将一个复杂对象的构建与它的表示分离 xff0c 使得同样的构建过程可以创建不同的表示 主要作用 在用户不知道对象的建造过程和细节的情况下就可以直接创建
  • 作为一名Web前端开发人员和设计师,2018告诉你如何正确的学习前端

    第一步 掌握HTML CSS 这是你最初必须 掌握的是网站的构建元素没得选 随着你前端的学习进程 熟练掌握HTML CSS简单易学这里还是要推荐下小编的web前端学习群 606加721加798 xff0c 不管你是小白还是大牛 xff0c
  • R语言对正交实验结果(含交互作用)进行极差分析与方差分析实例

    题目 某工厂为了提高某产品的收率 xff0c 根据经验和分析 xff0c 认为反应温度A 反应时间B 碱用量C和催化剂种类D可能对产品的收率造成较大的影响 并考虑交互作用AB xff0c AC 用正交表L8 27 安排试验 xff0c 试验
  • git突然pull push不了 一直fetching

    4 14 今天改完代码之后在idea中push的时候一直fetching xff0c 提交不了代码 改用命令push被拒绝 xff0c pull可以 xff0c 但是特别慢 首先考虑是公司要求定期更改密码 xff0c 但是排除 因为已经改了
  • 配置VNC图形界面服务

    第一步 xff1a 安装Gnome图形化界面 要能远程访问图形化界面 xff0c 首先服务器自身要安装图形化界面 xff0c 在此我们还要安装中文支持套件 yum groupinstall 34 X window System 34 34
  • Activity四种启动模式及onNewIntent()方法

    1 Standard xff1a 是活动默认的启动模式 xff0c 在不进行显式指定的情况下 xff0c 所有活动都会自动使用这种启动模式 系统不在乎这个活动是否已经在返回栈中存在 xff0c 每次启动都会创建该活动的一个新的实例 2 Si
  • Lnuix中查看pytorch和python安装版本和路径

    Lnuix中查看pytorch和python安装版本和路径 1 查看pytorch安装版本和路径 conda activate pytorch环境名称输入python查看版本号 span class token function impor
  • Python之FileNotFoundError: [Errno 2] No such file or directory问题处理

    错误信息 xff1a FileNotFoundError Errno 2 No such file or directory 39 AutoFrame temp report xlsx 39 相对于当前文件夹的路径 xff0c 其实就是你写
  • 基于centos7学习总结 -- shell脚本

    shell 脚本必须要以 34 bin bash 34 开头 脚本建议内容 xff1a 脚本的功能脚本的版本信息脚本的作者与联系方式脚本的版权声明方式脚本的History脚本内特殊的命令 xff0c 使用 绝对路径 的方式来执行脚本运行时需