Linux流程控制

if语句

基本格式
复制代码
if condition
then
    command1 
fi

写成一行

复制代码
if [ $(ps -ef | grep -c "ssh") -gt 1 ]; then echo "true"; fi
if-else语句
格式
复制代码
if condition
then
    command1 
    command2
    ...
    commandN
else
    command
fi

if else- if else

复制代码
if condition1
then
    command1
elif condition2 
then 
    command2
else
    commandN
fi
if实际应用
复制代码
#!/bin/bash
a=10
b=20
c=100
if [[ ! $a -eq $b && $b -lt $c ]]
then
        echo "a小于b并且c大于b"
fi
if ((a>b)) #可以使用(())代替,括号内可以使用<、>等符号,而且不需要加$符号,也可以加
then
        echo "a>b"
else
        echo "a<b"
fi

\]和(())的区别 * \`\[\]\`用于字符串或整数条件判断,可以执行大小写敏感的字符串比较、文件测试、逻辑运算、整数比较等,是一个更通用的条件判断方式。 * * \`(( ))\`用于整数条件判断,可以执行算术运算和逻辑运算,是专门用于整数运算的语句。需要注意的是,在使用\`(( ))\`时,变量名前面不需要加美元符号。 ## for语句 ##### 基本格式 for var in item1 item2 ... itemN do command1 command2 ... commandN done 写成一行 for var in item1 item2 ... itemN; do command1; command2... done; ##### 实例 #循环输出1 2 3 4 5这些值 for loop in 1 2 3 4 5 do echo "the value is :$loop" done #循环输出字符串 for str this is a cat do echo "$str" done #范围循环,学过c语言的应该很熟悉 for((i=0;i<10;i++)) do echo "i value: $i" done 输出结果 ![](https://file.jishuzhan.net/article/1788418433952518146/55d69cac0eacb476b4eebaf3c360bbb0.webp) ## while语句 ##### 基本格式 while condition do command done ##### 实例 判断 #!/bin/bash a=10 b=20 i=5 while(($i>=0)) do echo "$i" i=$((i-1)) #let "i--" 效果是一样的 done 读取录入信息 while read FILM do echo "您输入的是:$FILM" done 无限循环 while : do command done #或者 while true do command done #或者 for (( ; ; )) ## until语句 until语句与while刚好相反,循环执行直到条件为true时停止 ##### 基本格式 until condition do command done ##### 实例 until [ $a -ge 10 ] do echo $a a=`expr $a + 1` #a=$((¥a + 1)) 效果一样 done ## case语句 ##### 基本格式 case 值 in 模式1) command1 command2 ... commandN ;; 模式2) command1 command2 ... commandN ;; esac #两个分号表示break ##### 实例 输入判断 #!/bin/bash a=$1 echo $a case $a in 1) echo "您选择了1" ;; 2) echo "您选择了2" ;; 3) echo "您选择了3" ;; *) echo "您 的选择不在范围内" ;; esac ## break/continue ##### break 跳出所有循环 ##### continue 跳出当前循环

相关推荐
橙*^O^*安1 小时前
Go 语言基础:变量与常量
运维·开发语言·后端·golang·kubernetes
NiKo_W1 小时前
Linux 文件系统与基础指令
linux·开发语言·指令
阿拉斯加大闸蟹3 小时前
基于RDMA 通信的可负载均衡高性能服务架构
运维·架构·负载均衡
Darkwanderor3 小时前
Linux 的权限详解
linux
2301_780789663 小时前
渗透测试真的能发现系统漏洞吗
服务器·网络·安全·web安全·网络安全
SabreWulf20203 小时前
Ubuntu 20.04手动安装.NET 8 SDK
linux·ubuntu·avalonia·.net8
不是吧这都有重名3 小时前
为什么ubuntu大文件拷贝会先快后慢?
linux·运维·ubuntu
sunshine-sm4 小时前
CentOS Steam 9安装 Redis
linux·运维·服务器·redis·centos
小熊h4 小时前
MySQL集群高可用架构——组复制 (MGR)
linux·数据库·mysql
棒棒的唐4 小时前
armbian平台ubuntu环境下telnet安装及启动,给pantherX2增加一个应急通道
linux·运维·armbian·telnetd