linux shell(中)

server/2024/9/20 4:01:13/ 标签: linux, 运维

结构化命令

if语句

if-then

最基本的结构化命令是 if-then 语句。if-then 语句的格式如下:

if command
thencommands
ifif command; then  # 通过把分号(;)放在待求值的命令尾部,可以将 then 语句写在同一行commands
if

bash shell 的 if 语句会运行 if 之后的命令。如果该命令的退出状态码(参见第 11 章)为 0(命令成功运行),那么位于 then 部分的命令就会被执行。如果该命令的退出状态码是其他值,则 then 部分的命令不会被执行,bash shell 会接着处理脚本中的下一条命令。fi 语句用来表示if-then 语句到此结束。

#!/bin/bash
# testing the if statement 
if pwd  # if 行中的 pwd 命令,由于退出状态码是 0,会执行if-then 内部的语句
thenecho 'heheh'
if
#!/bin/bash
# testing an incorrect command
if IamNotCommand  # if 行中的 IamNotCommand 命令,由于命令不存在,不会执行if-then 内部的语句
thenecho 'heheh'
if
if-then-else

if-then-else 语句在语句中提供了另外一组命令

if command
thencommands
elsecommands
if
#!/bin/bash
# testing the else section
#
testuser=NoSuchUser
#
if grep $testuser /etc/passwd
thenecho "The script files in the home directory of $testuser are:"ls /home/$testuser/*.shecho
elseecho "The user $testuser does not exist on this system."echo
fi
echo "We are outside the if statement"

elif 语句行提供了另一个要测试的命令,这类似于原始的 if 语句行。

if command1
then            commands
elif command2
thenmore commands
fi    
test命令

test 命令可以在 if-then 语句中测试不同的条件。如果 test 命令中列出的条件成立,那么test 命令就会退出并返回退出状态码 0。如果条件不成立,那么 test 命令就会退出并返回非 0 的状态码,这使得 if-then 语句不会再被执行。

test 命令的格式非常简单:

test condition
if test condition
thencommands
fi

如果不写 test 命令的 condition 部分,则它会以非 0 的退出状态码退出。

使用 test 命令确定变量中是否为空:

#!/bin/bash
# testing if a variable has content
#
my_variable="Full"
#
if test $my_variable  # my_variable不是空,返回状态0
thenecho "The my_variable variable has content and returns a True."echo "The my_variable variable content is: $my_variable"
elseecho "The my_variable variable doesn't have content,"echo "and returns a False."
fi

bash shell 提供了另一种条件测试方式,无须在 if-then 语句中写明 test 命令:

if [ condition ]
then    commands
fi

方括号定义了测试条件。注意,第一个方括号之后和第二个方括号之前必须留有空格,否则就会报错。

test 命令和测试条件可以判断 3 类条件:

  • 数值比较(注意:不支持浮点数,只能用于整数)

  • 字符串比较

  • 文件比较

数值比较
比较描述
n1 -eq n2检查 n1 是否等于 n2
n1 -ge n2检查 n1 是否大于或等于 n2
n1 -gt n2检查 n1 是否大于 n2
n1 -le n2检查 n1 是否小于或等于 n2
n1 -lt n2检查 n1 是否小于 n2
n1 -ne n2检查 n1 是否不等于 n2
#!/bin/bash
# Using numeric test evaluations
#
value1=10
value2=11
#
if [ $value1 -gt 5 ]
thenecho "The test value $value1 is greater than 5."
fi
#
if [ $value1 -eq $value2 ]
thenecho "The values are equal."
elseecho "The values are different."
fi
字符串比较
比较描述
str1 = str2检查 str1 是否和 str2 相同
str1 > str2检查 str1 是否大于 str2
str1 < str2检查 str1 是否小于 str2
str1 != str2检查 str1 是否和 str2 不同
-n str1检查 str1 的长度是否不为 0
-z str1检查 str1 的长度是否为 0
#!/bin/bash
# Using string test evaluations
#
testuser=christine
#
if [ $testuser = christine ]
thenecho "The testuser variable contains: christine"
elseecho "The testuser variable contains: $testuser"
fi
文件比较
比较描述
-d file检查 file 是否存在且为目录
-e file检查 file 是否存在
-f file检查 file 是否存在且为文件
-r file检查 file 是否存在且可读
-s file检查 file 是否存在且非空
-w file检查 file 是否存在且可写
-x file检查 file 是否存在且可执行
-O file检查 file 是否存在且属当前用户所有
-G file检查 file 是否存在且默认组与当前用户相同
file1 -nt file2检查 file1 是否比 file2 新
file1 -ot file2检查 file1 是否比 file2 旧
#!/bin/bash
# 检查目录
#
jump_directory=/home/Torfa
#
if [ -d $jump_directory ]
thenecho "The $jump_directory directory exists."cd $jump_directoryls
elseecho "The $jump_directory directory does NOT exist."
fi
if-then的高级特性
  • 在子 shell 中执行命令的单括号

  • 用于数学表达式的双括号

  • 用于高级字符串处理功能的双方括号

单括号

单括号允许在 if 语句中使用子 shell。单括号形式的 test 命令格式如下:

(command)

在 bash shell 执行 command 之前,会先创建一个子 shell,然后在其中执行命令。如果命令成功结束,则退出状态码会被设为 0,then 部分的命令就会被执行。

#!/bin/bash
# Testing a single parentheses condition
#
echo $BASH_SUBSHELL
#
if (echo $BASH_SUBSHELL)
thenecho "The subshell command operated successfully."
#
elseecho "The subshell command was NOT successful."
#
fi

当脚本第一次(在 if 语句之前)执行 echo $BASH_SUBSHELL 命令时,是在当前 shell 中完成的。该命令会输出 0,表明没有使用子 shell($BASH_SUBSHELL :当前子 shell 环境的嵌套级别(初始值是 0))。在if 语句内,脚本在子 shell 中执行 echo $BASH_SUBSHELL 命令,该命令会输出 1,表明使用了子 shell。子 shell 操作成功结束,接下来是执行 then 部分的命令

双括号

双括号命令允许在比较过程中使用高级数学表达式。

符号描述
val++后增
val–后减
++val先增
–val先减
!逻辑求反
-位求反
**幂运算
<<左位移
>>右位移
&位布尔 AND
&&逻辑 AND
|逻辑OR
#!/bin/bash
# Testing a double parentheses command
#
val1=10
#
if (( $val1 ** 2 > 90 ))
then(( val2 = $val1 ** 2 ))echo "The square of $val1 is $val2,"echo "which is greater than 90."
#
fi
双方括号

双方括号命令提供了针对字符串比较的高级特性。双方括号的格式如下:

[[ expression ]]

expression 可以使用 test 命令中的标准字符串比较。除此之外,它还提供了 test 命令所不具备的另一个特性——模式匹配。

在进行模式匹配时,可以定义通配符或正则表达式

#!/bin/bash
# Using double brackets for pattern matching
#
#
if [[ $BASH_VERSION == 5.* ]]
thenecho "You are using the Bash Shell version 5 series."
fi
# 上述脚本中使用了双等号(==)。双等号会将右侧的字符串(5.*)视为一个模式并应用模式匹配规则。
# 双方括号命令会对$BASH_VERSION 环境变量进行匹配,看是否以字符串 5.起始。
# 如果是,则测试通过,shell 会执行 then 部分的命令。
Case命令

有了 case 命令,无须再写大量的 elif 语句来检查同一个变量的值了。case 命令会采用列表格式来检查变量的多个值:

case variable in
pattern1 | pattern2) commands1;;
pattern3) commands2;;
*) default commands;;
esac
#!/bin/bash
# Using a short case statement
#
case $USER in
rich | christine)echo "Welcome $USER"echo "Please enjoy your visit.";;
barbara | tim)echo "Hi there, $USER"echo "We're glad you could join us.";;
testing)echo "Please log out when done with test.";;
*)echo "Sorry, you are not allowed here."
esac
$

循环

for

bash shell 提供了 for 命令,以允许创建遍历一系列值的循环。每次迭代都使用其中一个值来执行已定义好的一组命令。for 命令的基本格式如下:

for var in list
docommands
done
#!/bin/bash
# basic for command 读取列表中的值
for test in Alabama Alaska Arizona Arkansas California Colorado
doecho The next state is $test
done

for 命令使用空格来划分列表中的每个值。如果某个值含有空格,则必须将其放入双引号内

#!/bin/bash
# an example of how to properly define values
for test in Nevada "New Hampshire" "New Mexico" "New York"
doecho "Now going to $test"
done
可以从变量中读取列表
#!/bin/bash
# using a variable to hold the list
list="Alabama Alaska Arizona Arkansas Colorado"
list=$list" Connecticut"
for state in $list # 
doecho "Have you ever visited $state?"
done

$list 变量包含了用于迭代的值列表。注意,脚本中还使用了另一个赋值语句向$list 变量包含的值列表中追加(或者说是拼接)了一项。这是向变量中已有的字符串尾部添加文本的一种常用方法。

从命令中读取值列表
#!/bin/bash
# reading values from a file
file="states.txt"
for state in $(cat $file)
doecho "Visit beautiful $state"
done

使用 cat 命令来输出文件 states.txt 的内容,states.txt 文件中每
个值各占一行,而不是以空格分隔。

更改字段分割符

IFS环境变量定义了 bash shell 用作字段分隔符的一系列字符。在默认情况下,bash shell 会将下列字
符视为字段分隔符:

  • 空格

  • 制表符

  • 换行符

如果 bash shell 在数据中看到了这些字符中的任意一个,那么它就会认为这是列表中的一个新字段的开始。

可以在 shell 脚本中临时更改 IFS 环境变量的值,指定字段分隔符的字符。

#!/bin/bash
# reading values from a file
file="states.txt"IFS.OLD=$IFS
IFS=$'\n'  # 告诉 bash shell 忽略数据中的空格和制表符
for state in $(cat $file)
doecho "Visit beautiful $state"
done
IFS=$IFS.OLD # 恢复默认值,保证后续使用默认值的操作能正常运行# IFS=:   # 如果要遍历文件中以冒号分隔的值,则只需将 IFS 的值设为冒号即可# IFS=$'\n:;"'  # 将换行符、冒号、分号和双引号作为字段分隔符
使用通配符读取目录
#!/bin/bash
# iterate through all the files in a directory
for file in /home/rich/test/*
doif [ -d "$file" ]thenecho "$file is a directory"elif [ -f "$file" ]thenecho "$file is a file"fi
done
#!/bin/bash
# 可以在 for 命令中列出多个目录通配符
for file in /home/rich/.b* /home/rich/badtest
doif [ -d "$file" ]thenecho "$file is a directory"elif [ -f "$file" ]thenecho "$file is a file"elseecho "$file doesn't exist"fi
done
C 语言风格的 for 命令

bash 中仿 C 语言的 for 循环的基本格式如下:

for (( variable assignment ; condition ; iteration process ))# demo
for (( a = 1; a < 10; a++ ))

注意,有些地方与 bash shell 标准的 for 命令并不一致:

  • 变量赋值可以有空格

  • 迭代条件中的变量不以美元符号开头

  • 迭代过程的算式不使用 expr 命令格式

#!/bin/bash
# testing the C-style for loopfor (( i=1; i <= 10; i++ ))
doecho "The next number is $i"
done

仿 C 语言的 for 命令也允许为迭代使用多个变量

#!/bin/bash
# multiple variables
for (( a=1, b=10; a <= 10; a++, b-- ))
doecho "$a - $b"
done
while

while 命令在某种程度上糅合了 if-then 语句和 for 循环。while 命令的格式如下:

while test command
doother commands
done

while 命令中定义的 test command 与 if-then 语句中的格式一模一样。可以使用任何 bash shell 命令,或者用 test command 进行条件测试。

while 命令的关键在于所指定的 test command 的退出状态码必须随着循环中执行的命令而改变。如果退出状态码不发生变化,那 while 循环就成了死循环。

#!/bin/bash
# while command test
var1=10
while [ $var1 -gt 0 ]
doecho $var1var1=$[ $var1 - 1 ]
done

while 命令允许在 while 语句行定义多个测试命令。只有最后一个测试命令的退出状态码会被用于决定是否结束循环

#!/bin/bash
# testing a multicommand while loop
var1=10
while echo $var1[ $var1 -ge 0 ]
doecho "This is inside the loop"var1=$[ $var1 - 1 ]
done
until

与 while 命令工作的方式完全相反,until 命令要求指定一个返回非 0 退出状态码的测试命令。只要测试命令的退出状态码不为 0,bash shell 就会执行循环中列出的命令。一旦测试命令返回了退出状态码 0,循环就结束了。

until test command
doother commands
done
循环控制
breadk

break 命令是退出循环的一种简单方法。你可以用 break 命令退出任意类型的循环,包括while 循环和 until 循环。

#!/bin/bash
# breaking out of a for loop
for var1 in 1 2 3 4 5 6 7 8 9 10
doif [ $var1 -eq 5 ]thenbreakfiecho "Iteration number: $var1"
done
echo "The for loop is completed"

在处理多个循环时,break 命令会自动结束你所在的最内层循环:

#!/bin/bash
# breaking out of an inner loop
for (( a = 1; a < 4; a++ ))
doecho "Outer loop: $a"for (( b = 1; b < 100; b++ ))doif [ $b -eq 5 ]thenbreak  # 结束内层循环fiecho " Inner loop: $b"done
done

有时你位于内层循环,但需要结束外层循环。break 命令接受单个命令行参数:

break n

其中 n 指定了要跳出的循环层级。在默认情况下,n 为 1,表明跳出的是当前循环。如果将 n 设为 2,那么 break 命令就会停止下一级的外层循环:

#!/bin/bash
# breaking out of an outer loop
for (( a = 1; a < 4; a++ ))
doecho "Outer loop: $a"for (( b = 1; b < 100; b++ ))doif [ $b -gt 4 ]thenbreak 2 # 结束外层循环fiecho " Inner loop: $b"done
done
continue

continue 命令可以提前中止某次循环,但不会结束整个循环。你可以在循环内部设置 shell不执行命令的条件。

#!/bin/bash
# using the continue command
for (( var1 = 1; var1 < 15; var1++ ))
doif [ $var1 -gt 5 ] && [ $var1 -lt 10 ]thencontinuefiecho "Iteration number: $var1"
done

也可以在 while 循环和 until 循环中使用 continue 命令,但要特别小心。记住,当 shell执行 continue 命令时,它会跳过剩余的命令


http://www.ppmy.cn/server/88894.html

相关文章

git stash 命令详解

git stash 描述 git stash 命令用于将当前工作目录中的未提交更改&#xff08;包括暂存区和工作区的更改&#xff09;保存到一个栈中&#xff0c;并恢复工作目录到干净的 HEAD 状态。这样您可以在不提交当前更改的情况下&#xff0c;切换到其他分支或进行其他操作。后续可以通…

Golang使用docker sdk管理docker

包括列出容器、创建容器、删除容器、进入容器、构建镜像等操作。 package dockertoolimport ("context""fmt""github.com/docker/docker/api/types""github.com/docker/docker/api/types/container""github.com/docker/docker/ap…

微服务安全——OAuth2.1详解、授权码模式、SpringAuthorizationServer实战、SSO单点登录、Gateway整合OAuth2

文章目录 Spring Authorization Server介绍OAuth2.0协议介绍角色OAuth2.0协议的运行流程应用场景授权模式详解客户端模式密码模式授权码模式简化模式token刷新模式 OAuth 2.1 协议介绍授权码模式PKCE扩展设备授权码模式拓展授权模式 OpenID Connect 1.0协议Spring Authorizatio…

java对接soap工具类-callSonyInterfaceQuery

新写的工具类&#xff0c;其中有对接soap的工具类 import com.shutong.common.exception.ServiceException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.Cont…

基于jeecgboot-vue3的Flowable流程仿钉钉流程设计器-抄送服务处理

因为这个项目license问题无法开源&#xff0c;更多技术支持与服务请加入我的知识星球。 1、因为仿钉钉设计器里抄送人是一个服务任务&#xff0c;所以要根据这个服务任务进行处理 2、前端就是一个抄送&#xff0c;选择人 3、这里用了jeecg的选择人组件 <el-form-item prop…

LongAlign:大模型长文本处理能力提升之道

人工智能咨询培训老师叶梓 转载标明出处 大模型&#xff08;LLMs&#xff09;在处理长文本时&#xff0c;需要在输入序列上进行指令微调&#xff08;instruction finetuning&#xff09;&#xff0c;以确保它们能够有效地处理长文本。现有的方法主要集中在上下文扩展&#xff0…

Qt第十三章 目录和文件操作

目录和文件操作 文章目录 目录和文件操作设备I/O简介I/O设备的类型基本文件读写QFileQTemporaryFile 流操作QTextStreamQDataStream QFileInfoQDirQFileSystemWatcherQStandardPathsQSettings 设备I/O 简介 I/O设备的类型 基本文件读写 QFile QFile file("C:/Users/PV…

C++ | Leetcode C++题解之第278题第一个错误的版本

题目&#xff1a; 题解&#xff1a; class Solution { public:int firstBadVersion(int n) {int left 1, right n;while (left < right) { // 循环直至区间左右端点相同int mid left (right - left) / 2; // 防止计算时溢出if (isBadVersion(mid)) {right mid; // 答案…

力扣984.不含AAA或BBB的字符串

力扣984.不含AAA或BBB的字符串 贪心 如下 class Solution {public:string strWithout3a3b(int a, int b) {string res;while(a > b && b > 0){res "aab";a--,a--;b--;}while(b > a && a > 0){res "bba";b--,b--;a--;}whi…

C#实现数据采集系统-modbustcp数据通知

实现数据推送 在ModbusTcp模块中已经能够获取到正确的plc值,接下来做的就是如何让外部调用的程序获取到相关的数据,主要就是两种方法:通过对象属性进行共享;通过事件进行推送 方法一:通过类属性共享 在RegisterPoint类中增加public object Value { get; set; }value属性…

算法之递归算法

递归是非常常见的一种算法&#xff0c; 也比较难以理解&#xff0c;简而言之&#xff0c;递归就是写了一个方法&#xff0c;方法中还调用了该方法&#xff0c;相当于自己调用自己&#xff0c;如果书写不当&#xff0c;就会有堆栈溢出的风险&#xff0c;无法跳出。 所以我们编写…

【CTFWP】ctfshow-web36

文章目录 题目介绍&#xff1a;题目分析&#xff1a;payload&#xff1a;payload解释&#xff1a;flag 题目介绍&#xff1a; <?php/* # -*- coding: utf-8 -*- # Author: h1xa # Date: 2020-09-04 00:12:34 # Last Modified by: h1xa # Last Modified time: 2020-09-…

Power App学习笔记以及基础项目管理demo

Power App学习笔记以及基础项目管理demo 最近学习了一点Power App&#xff0c;感觉挺有意思。配置式组件开发。浅浅记录一下自己实现的项目管理系统&#xff08;即Excel数据的增删改查&#xff09;关于函数的一点皮毛认识。 效果图 筛选数据 编辑 详情 数据源 PowerApp 网…

河北省高校大数据人工智能实验室案例分享

随着大数据和人工智能技术的快速发展&#xff0c;教育领域也迎来了前所未有的变革机遇。泰迪智能科技作为一家专注于大数据与人工智能领域的高新技术企业&#xff0c;一直致力于将前沿技术引入教育行业&#xff0c;助力高校培养更多具有创新能力和实战经验的复合型人才。本次案…

PHP Switch 语句

PHP 中的 switch 语句是一种多路分支语句&#xff0c;它允许一个变量的值对多个代码块进行选择执行。这通常比使用多个 if...elseif...else 语句更清晰、更易于维护。下面将详细介绍 PHP 中 switch 语句的使用方法。 基本语法 switch (n) {case label1:// 如果 n label1&…

<Python><paddle>基于python使用百度paddleocr实现车牌识别

前言 paddleocr是百度飞桨的一个文字识别库&#xff0c;准确度非常高&#xff0c;基于其文字识别的基础&#xff0c;将其用于车牌识别。这个识别的准确度是相当高的。 环境配置 系统&#xff1a;windows 平台&#xff1a;visual studio code 语言&#xff1a;python 库&#…

oracle使用backup as copy方式迁移数据文件

oracle使用backup as copy方式迁移数据文件 1 基础环境 --确认数据文件路径 set line 200 col name for a75 select file#,name from v$datafileFILE# NAME ---------- ---------------------------------------------------------------------------1 /u01/app/oracle/orada…

一些和颜色相关网站

1.中国传统色 2.网页颜色选择器 3.渐变色网站 4.多风格色卡生成 5.波浪生成 6.半透明磨砂框 7.色卡组合

MAC配置环境变量

MAC配置环境变量的地方 1./ext/profile(建议不修改这个文件) 全局&#xff08;共有&#xff09;配置一般不管那个用户&#xff0c;登陆时都会读取该文件。 2./ext.bashrc(一般在这个文件中添加系统级环境变量) 全局&#xff08;公有&#xff09;配置&#xff0c;bash shel…