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