Shell编程——弱数据类型的脚本语言快速入门指南

目录

Linux Shell

数据类型

变量类型

运算符

算术运算符

赋值运算符

拼接运算符

比较运算符

关系运算符

控制结构

顺序结构

条件分支结构

if 条件语句

case 分支语句 

循环结构

for 循环

while 循环

until 循环

break 语句

continue语句

函数

函数定义 

函数名

函数体

返回值

参数

函数的局部性

简单函数示例

函数的递归

实例操作

数组遍历操作

九九乘法表


基本上,每一门编程语言,都能从数据类型、变量、运算符、控制结构、函数五个方面着手,初步掌握这些内容就可以快速入门为一名初级程序员。

Linux Shell

Shell是Linux命令行解释器,主要用于执行操作系统命令和脚本。Linux Shell编程语言是一种用于与操作系统内核进行交互的命令行脚本语言,属于解释型、弱类型的动态语言。

数据类型

bool、数字、字符串、数组

变量类型

环境变量、用户变量、全局变量、只读变量

set let export readonly  env

运算符

算术运算符

+ - * / %

赋值运算符

=,没有+=、-=、*=、/=这类复合赋值

拼接运算符

+= ,只能用于字符串的拼接

比较运算符

==、!=

关系运算符

-eq    检测两个数是否相等,相等返回 true。
-ne    检测两个数是否不相等,不相等返回 true。
-gt    检测左边的数是否大于右边的,如果是,则返回 true。
-lt    检测左边的数是否小于右边的,如果是,则返回 true。
-ge    检测左边的数是否大于等于右边的,如果是,则返回 true。
-le    检测左边的数是否小于等于右边的,如果是,则返回 true。

控制结构

顺序结构

顺序结构是最简单的算法结构,语句与语句之间是按从上到下的顺序进行的,它是由若干个依次执行的处理步骤组成的。

注:同一行可以有多个语句,只要用分号“;”来分隔即可。

条件分支结构

if 条件语句

可以细分为 if , if-else , if-elif-else 多种形式

hann@HannYang:~$ help -m if
NAMEif - Execute commands based on conditional.SYNOPSISif COMMANDS; then COMMANDS; [ elif COMMANDS; then COMMANDS; ]... [ else COMMANDS; ] fiDESCRIPTIONExecute commands based on conditional.The `if COMMANDS' list is executed.  If its exit status is zero, then the`then COMMANDS' list is executed.  Otherwise, each `elif COMMANDS' list isexecuted in turn, and if its exit status is zero, the corresponding`then COMMANDS' list is executed and the if command completes.  Otherwise,the `else COMMANDS' list is executed, if present.  The exit status of theentire construct is the exit status of the last command executed, or zeroif no condition tested true.Exit Status:Returns the status of the last command executed.......

case 分支语句 

hann@HannYang:~$ help -m case
NAMEcase - Execute commands based on pattern matching.SYNOPSIScase WORD in [PATTERN [| PATTERN]...) COMMANDS ;;]... esacDESCRIPTIONExecute commands based on pattern matching.Selectively execute COMMANDS based upon WORD matching PATTERN.  The`|' is used to separate multiple patterns.Exit Status:Returns the status of the last command executed.......

循环结构

for 循环

hann@HannYang:~$ help -m for
NAMEfor - Execute commands for each member in a list.SYNOPSISfor NAME [in WORDS ... ] ; do COMMANDS; doneDESCRIPTIONExecute commands for each member in a list.The `for' loop executes a sequence of commands for each member in alist of items.  If `in WORDS ...;' is not present, then `in "$@"' isassumed.  For each element in WORDS, NAME is set to that element, andthe COMMANDS are executed.Exit Status:Returns the status of the last command executed.......

while 循环

hann@HannYang:~$ help -m while
NAMEwhile - Execute commands as long as a test succeeds.SYNOPSISwhile COMMANDS; do COMMANDS; doneDESCRIPTIONExecute commands as long as a test succeeds.Expand and execute COMMANDS as long as the final command in the`while' COMMANDS has an exit status of zero.Exit Status:Returns the status of the last command executed.......

until 循环

hann@HannYang:~$ help -m until
NAMEuntil - Execute commands as long as a test does not succeed.SYNOPSISuntil COMMANDS; do COMMANDS; doneDESCRIPTIONExecute commands as long as a test does not succeed.Expand and execute COMMANDS as long as the final command in the`until' COMMANDS has an exit status which is not zero.Exit Status:Returns the status of the last command executed.......

break 语句

hann@HannYang:~$ help -m break
NAMEbreak - Exit for, while, or until loops.SYNOPSISbreak [n]DESCRIPTIONExit for, while, or until loops.Exit a FOR, WHILE or UNTIL loop.  If N is specified, break N enclosingloops.Exit Status:The exit status is 0 unless N is not greater than or equal to 1.......

continue语句

hann@HannYang:~$ help -m continue
NAMEcontinue - Resume for, while, or until loops.SYNOPSIScontinue [n]DESCRIPTIONResume for, while, or until loops.Resumes the next iteration of the enclosing FOR, WHILE or UNTIL loop.If N is specified, resumes the Nth enclosing loop.Exit Status:The exit status is 0 unless N is not greater than or equal to 1.......

两者的区别 

break语句:

break语句用于退出本层循环,当执行到break会立即跳出当前循环,执行后续代码。
在多层嵌套循环中,break只会跳出最近的一层循环。

continue语句:

continue语句用于结束本次循环,跳过本次循环中剩余的代码,直接进入下一次循环。
在多层嵌套循环中,continue只会跳过最近的一层循环。

函数

hann@HannYang:~$ help -m function
NAMEfunction - Define shell function.SYNOPSISfunction name { COMMANDS ; } or name () { COMMANDS ; }DESCRIPTIONDefine shell function.Create a shell function named NAME.  When invoked as a simple command,NAME runs COMMANDs in the calling shell's context.  When NAME is invoked,the arguments are passed to the function as $1...$n, and the function'sname is in $FUNCNAME.Exit Status:Returns success unless NAME is readonly.

函数定义 

函数名

Shell函数用关键字 function 声明,跟在后面的 name 即函数名。声明后就用"函数名 [参数]"来调用函数。function 非必须,也能用函数名加一对括号 name() { ... } 来声明定义函数。

函数体

函数名后的 { Commands; } 即函数体,是实现函数功能的主体。

返回值

Shell函数可以有一个返回值,可以使用return语句返回一个值。返回值的范围是0到255之间,0表示成功,非零值表示错误。如果函数中没有return语句,或者使用exit命令退出函数,则函数的返回值为退出命令的返回值。

参数

Shell函数可以通过参数接收输入的值。在函数定义时,可以在括号中指定参数列表。参数可以在函数体中使用,也可以通过特殊变量$#获取函数的参数个数,通过特殊变量$@获取所有的参数。

函数的局部性

Shell函数的变量是局部的,即在函数内部定义的变量只在该函数内部可见,不会影响到函数外部的变量。如果要使用全局变量,需要在函数外部定义。

简单函数示例

hann@HannYang:~$ function add {
>     num1=$1
>     num2=$2
>     sum=$((num1 + num2))
>     echo "The sum of $num1 and $num2 is $sum."
> }
hann@HannYang:~$ add 10 20
The sum of 10 and 20 is 30.

 语句比较少的函数可以在一行内完成,函数体中的语句间用分号“;”来分隔即可。

hann@HannYang:~$ function sub { num1=$1; num2=$2; sum=$((num1 - num2)); echo "The difference between $num1 and $num2 is $sum."; }
hann@HannYang:~$ sub 30 20
The difference between 30 and 20 is 10.

函数的递归

Shell函数可以递归调用自身,这在处理嵌套数据结构或递归算法时非常有用。需要注意的是,递归调用可能会导致栈溢出或效率低下的问题,因此在使用时需要谨慎。

示例:阶乘函数

hann@HannYang:~$ factorial() {
>     if [ $1 -le 1 ]
>     then
>         echo 1
>     else
>         echo $(( $1 * $(factorial $(( $1 - 1 ))) ))
i
}>     fi
> }
hann@HannYang:~$ read -p "请输入一个整数:" num
请输入一个整数:6
hann@HannYang:~$ result=$(factorial $num)
hann@HannYang:~$ echo "$num 的阶乘为 $result"
6 的阶乘为 720

实例操作

数组遍历操作

hann@HannYang:~$ for i in 1 2 3 4 5; do echo -n $i; done; echo
12345
hann@HannYang:~$ for i in {1..5}; do echo -n $i; done; echo
12345
hann@HannYang:~$ sum=0;for i in {1..100};do let sum+=i;done;echo $sum
5050
hann@HannYang:~$ for i in {1..5}{8..10}; do echo -n $i; done; echo
18191102829210383931048494105859510
hann@HannYang:~$ for i in {1..5}{8..10}; do echo -n $i" "; done; echo
18 19 110 28 29 210 38 39 310 48 49 410 58 59 510
hann@HannYang:~$ for i in {A..C}{a..d}; do echo -n $i" "; done; echo
Aa Ab Ac Ad Ba Bb Bc Bd Ca Cb Cc Cd

九九乘法表

hann@HannYang:~$ cat 99mul.sh

#!/bin/bashfor i in {1..9}
dofor j in {1..9}doif [ $j -le $i ]thenecho -n "$j*$i=$(($i*$j)) "fidoneecho ""
done

hann@HannYang:~$ bash 99mul.sh

1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9
1*4=4 2*4=8 3*4=12 4*4=16
1*5=5 2*5=10 3*5=15 4*5=20 5*5=25
1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36
1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49
1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64
1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81

hann@HannYang:~$ cat 99mul.sh

#!/bin/bashfor i in {1..9}
dofor j in {1..9}doif [ $j -le $i ]thenprintf "%d*%d=%2d " $j $i $(($i*$j))fidoneecho ""
done

hann@HannYang:~$ bash 99mul.sh

1*1= 1
1*2= 2 2*2= 4
1*3= 3 2*3= 6 3*3= 9
1*4= 4 2*4= 8 3*4=12 4*4=16
1*5= 5 2*5=10 3*5=15 4*5=20 5*5=25
1*6= 6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36
1*7= 7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49
1*8= 8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64
1*9= 9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81

hann@HannYang:~$ cat 99mul.sh 

#!/bin/bashfor i in {1..9}
dofor j in {1..9}doif [ $j -le $i ]thenif [ $j -eq 1 ]thenprintf "%d*%d=%d " $j $i $(($i*$j))elseprintf "%d*%d=%2d " $j $i $(($i*$j))fifidoneecho ""
done

hann@HannYang:~$ bash 99mul.sh

1*1=1
1*2=2 2*2= 4
1*3=3 2*3= 6 3*3= 9
1*4=4 2*4= 8 3*4=12 4*4=16
1*5=5 2*5=10 3*5=15 4*5=20 5*5=25
1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36
1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49
1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64
1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81


本文简单提一下Linux Shell编程语言的入门要点,之后再对各个环节进行分类详细举例说明。

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

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

相关文章

Stable Diffusion Webui源码剖析

1、关键python依赖 (1)xformers:优化加速方案。它可以对模型进行适当的优化来加速图片生成并降低显存占用。缺点是输出图像不稳定,有可能比不开Xformers略差。 (2)GFPGAN:它是腾讯开源的人脸修…

大数据扫盲(1): 数据仓库与ETL的关系及ETL工具推荐

在数字化时代,数据成为了企业决策的关键支持。然而,随着数据不断增长,有效地管理和利用这些数据变得至关重要。数据仓库和ETL工具作为数据管理和分析的核心,将帮助企业从庞杂的数据中提取有价值信息。 一、ETL是什么? …

【不限于联想Y9000P电脑关盖再打开时黑屏的解决办法】

不限于联想Y9000P电脑关盖再打开时黑屏的解决办法 问题的前言问题的出现问题拟解决 问题的前言 事情发生在昨天,更新了Win11系统后: 最惹人注目的三处地方就是: 1.可以查看时间的秒数了; 2.右键展示的内容变窄了; 3.按…

Pycharm 双击启动失败?

事故 双击 Pycharm 后,出现加载工程,我不想加载这个工程,就点击了弹出的 cancle 取消按钮。然后再到桌面双击 Pycharm 却发现无法启动了。哪怕以管理员权限运行也没用,就是不出界面。 原因未知 CtrlshiftESC 打开后台&#xff…

【腾讯云 Cloud Studio 实战训练营】Hexo 框架 Butterfly 主题搭建个人博客

什么是Cloud Studio Cloud Studio 是基于浏览器的集成式开发环境(IDE),为开发者提供了一个永不间断的云端工作站。用户在使用 Cloud Studio 时无需安装,随时随地打开浏览器就能在线编程。 ​ Hexo 博客成品展示 本人博客如下&…

【Spring】-Spring项目的创建

作者:学Java的冬瓜 博客主页:☀冬瓜的主页🌙 专栏:【Framework】 主要内容:创建spring项目的步骤:先创建一个maven项目,再在pom.xml中添加spring框架支持,最后写一个启动类。 文章目…

Field injection is not recommended

文章目录 1. 引言2. 不推荐使用Autowired的原因3. Spring提供了三种主要的依赖注入方式3.1. 构造函数注入(Constructor Injection)3.2. Setter方法注入(Setter Injection)3.3. 字段注入(Field Injection) 4…

计算机视觉五大核心研究任务全解:分类识别、检测分割、人体分析、三维视觉、视频分析

目录 一、引言1.1 计算机视觉的定义1.1.1 核心技术1.1.2 应用场景 1.2 历史背景及发展1.2.1 1960s-1980s: 初期阶段1.2.2 1990s-2000s: 机器学习时代1.2.3 2010s-现在: 深度学习的革命 1.3 应用领域概览1.3.1 工业自动化1.3.2 医疗图像分析1.3.3 自动驾驶1.3.4 虚拟现实与增强现…

山东布谷科技直播软件开发WebRTC技术:建立实时通信优质平台

在数字化的时代,实时通信成为了人们远程交流的主要方式,目前市场上也出现了很多带有实时通信交流的软件,实时通信符合人们现在的需求,所以在直播软件开发过程中,开发者也运用了实时通信技术为直播软件加入了实时通信的…

【计算机视觉|生成对抗】生成对抗网络(GAN)

本系列博文为深度学习/计算机视觉论文笔记,转载请注明出处 标题:Generative Adversarial Nets 链接:Generative Adversarial Nets (nips.cc) 摘要 我们提出了一个通过**对抗(adversarial)**过程估计生成模型的新框架…

2.阿里云对象存储OSS

1.对象存储概述 文件上传,是指将本地图片、视频、音频等文件上传到服务器上,可以供其他用户浏览或下载的过程。文件上传在项目中应用非常广泛,我们经常发抖音、发朋友圈都用到了文件上传功能。 实现文件上传服务,需要有存储的支持…

【概念理解】STM32中的sprintf()函数

sprintf()函数 这个函数在 stdio.h中;可以将格式化的数据写入到一个字符串缓冲区中。 int sprintf(char *str, const char *format, ...);str:指向字符数组的指针,即用于存储格式化后字符串的缓冲区。format:格式化字符串&#…

(十六)大数据实战——安装使用mysql版的hive服务

前言 hive默认使用的是内嵌据库derby,Derby 是一个嵌入式数据库,可以轻松地以库的形式集成到应用程序中。它不需要独立的服务器进程,所有的数据存储在应用程序所在的文件系统中。为了支持hive服务更方便的使用,我们使用mysql数据…

【实战】十一、看板页面及任务组页面开发(一) —— React17+React Hook+TS4 最佳实践,仿 Jira 企业级项目(二十三)

文章目录 一、项目起航:项目初始化与配置二、React 与 Hook 应用:实现项目列表三、TS 应用:JS神助攻 - 强类型四、JWT、用户认证与异步请求五、CSS 其实很简单 - 用 CSS-in-JS 添加样式六、用户体验优化 - 加载中和错误状态处理七、Hook&…

c语言每日一练(8)

前言:每日一练系列,每一期都包含5道选择题,2道编程题,博主会尽可能详细地进行讲解,令初学者也能听的清晰。每日一练系列会持续更新,暑假时三天之内必有一更,到了开学之后,将看学业情…

【javaweb】学习日记Day1 - HTML CSS入门

目录 一、图片标签 ① 绝对路径 1.绝对磁盘路径 2.绝对网络路径 ② 相对路径 (推荐) 二、标题标签 三、水平线标签 四、标题样式 1、CSS引入样式 ① 行内样式 ② 内嵌样式 ③ 外嵌样式 2、CSS选择器 ① 元素选择器 ② id选择器 ③…

Hadoop+Python+Django+Mysql热门旅游景点数据分析系统的设计与实现(包含设计报告)

系统阐述的是使用热门旅游景点数据分析系统的设计与实现,对于Python、B/S结构、MySql进行了较为深入的学习与应用。主要针对系统的设计,描述,实现和分析与测试方面来表明开发的过程。开发中使用了 django框架和MySql数据库技术搭建系统的整体…

Python批量给excel文件加密

有时候我们需要定期给公司外部发邮件,在自动化发邮件的时候需要对文件进行加密传输。本文和你一起来探索用python给单个文件和批量文件加密。    python自动化发邮件可参考【干货】用Python每天定时发送监控邮件。 文章目录 一、安装pypiwin32包二、定义给excel加…

【Docker】Docker使用之容器技术发展史

🎬 博客主页:博主链接 🎥 本文由 M malloc 原创,首发于 CSDN🙉 🎄 学习专栏推荐:LeetCode刷题集 🏅 欢迎点赞 👍 收藏 ⭐留言 📝 如有错误敬请指正&#xff0…

【Unity】UI的一些简单知识

Canvas 新建一个Canvas Render Mode Canvas 中有一个Render Mode(渲染模式),有三种渲染模式: Screen Space-Overlay (屏幕空间)Screen Space-Camara 、 World Space 其中,Space- Overlay是默认显示在…