当前位置: 首页 > news >正文

shell脚本的【算数运算、分支结构、test表达式】

1.思维导图 

2.test表达式

2.1 格式

shell中的单分支
if [ test语句 ];then    ----> if test 表达式;thentest语句成立执行的语句块
fi
if [ test语句 ]      ----> if test 表达式
thentest语句成立执行的语句块
fi双分支
if [ test语句 ]
thentest语句成立执行的语句块
elsetest语句不成立执行的语句块
fi多分支
if [ test语句1 ]
thentest语句1成立执行的语句块
elif [ test语句2 ]
thentest语句1不成立,但test语句2成立执行阿语句块
fi嵌套if
if [ test语句1 ]
thentest语句1成立执行的语句块if [ test语句2 ]thentest语句1和test语句2都成立执行的语句块fi
fi

2.2 test表达式

2.2.1 整数判断

判断平年闰年
#!/bin/bashread -p "Enter a year: " yearif [ $((year%4)) -eq 0 ]  &&  [ $((year%100)) -ne 0 ] || [ $((year%400)) -eq 0 ]; 
thenecho "$year  闰年"
elseecho "$year 平年"
fi

2.2.2字符串判断

str1=h
str2=w
if [ $str1 = $str2 ] #判断两个字符串是否相等
thenecho str1==str2
elif [ $str1 != $str2 ] #判断两个字符串是否不相等
thenecho str1!=str2

2.2.3文件判断 

输入一个脚本名,判断该脚本是否存在,如果存在判断是否有可执行权限,如果有执行脚本,如果没有添加可执行权限再执行脚本

#!/bin/bash
read -p "enter name of shell"  shell
if [ -e "./$shell" ]
thenecho "$shell exist"if [ -x "./$shell" ]then bash $shellelseecho "$shell not executable"chmod a+x "./$shell"bash $shellfi
fi

 3.作业

1..终端输入一个C源文件名(.c结尾)判断文件是否有内容,如果没有内容删除文件,如果有内容
编译并执行改文件

read -p "Enter C file : " cfile# 检查文件是否存在且是 .c 文件
if [[ -e "$cfile" && "$cfile" == *.c ]]; then# 检查文件是否有内容if [ ! -s "$cfile" ]; thenecho "$cfile is empty, deleting the file"rm "$cfile"elseecho "$cfile has content, compiling"# 编译 C 文件,生成默认的 a.outgcc "$cfile"# 检查是否生成了目标文件 a.outif [ -f "a.out" ]; thenecho "Compilation successful. Running the program"./a.outelseecho "Compilation failed. No a.out file "fifi
elseecho "The file does not exist or  not a .c file."
fi


2.终端输入两个文件名,判断哪个文件的时间戳更新。

# 提示用户输入两个文件名
read -p "enter the first file name: " file1
read -p "enter the second file name: " file2# 检查文件是否存在
if [[ -e "$file1" && -e "$file2" ]]; then# 比较文件的时间戳if [ "$file1" -nt "$file2" ]; thenecho "$file1 is new than $file2."elif [ "$file1" -ot "$file2" ]; thenecho "$file2 is new  than $file1."elseecho "same time."fi
else# 如果有任意一个文件不存在if [ ! -e "$file1" ]; thenecho " $file1 not exist."fiif [ ! -e "$file2" ]; thenecho " $file2 not exist."fi
fi


http://www.mrgr.cn/news/82221.html

相关文章:

  • 【Quest开发】手柄单手抓握和双手抓握物体切换
  • css动画水球图
  • HTML<center>标签
  • skywalking的使用
  • Deformable Detr回顾
  • Kutools for Excel 简体中文版 - 官方正版授权
  • 03-类和对象(上)
  • SQL偏移类窗口函数—— LAG()、LEAD()用法详解
  • 单片机-蜂鸣器实验
  • vue视频录制 限制大小,限制时长
  • 思科无线控制器 AC5508 初始化
  • 操作系统课后题总复习
  • SpringCloud源码-Ribbon
  • Docker Compose编排
  • spring boot通过文件配置yaml里面的属性
  • Spring实现Logback日志模板设置动态参数
  • 19712 数字接龙
  • TTL 传输中过期问题定位
  • FOC控制原理7-源码解析2-系统滴答定时器中断
  • 使用ebooklib制作符合epub3规范的epub文件
  • C++语言编程————C++数据类型
  • 解决virtualbox克隆ubuntu虚拟机之后IP重复的问题
  • java Redisson 实现限流每秒/分钟/小时限制N个
  • 【复刻】ESG表现对企业价值的影响机制研究(2009-2021年)
  • 一、VxLAN 简介
  • 旷视科技Java面试题及参考答案