1、测试文件c/thread.c是否存在
命令:test -e c/thread.c
echo $?
结果:
2、编写Shell脚本文件testrwx.sh,对文件拥有的属性进行判断
脚本:
#!/bin/bash
read -p "你想测试哪个文件?" filename
if [ ! -e "$filename" ]; then
echo "这个文件不存在。"
#exit 1
fi
if [ -r "$filename" ]; then
echo "$filename是可读的。"
#exit 1
fi
if [ -w "$filename" ]; then
echo "$filename是可写的。"
#exit 1
fi
if [ -x "$filename" ]; then
echo "$filename是可执行的。"
#exit 1
fi
命令:. ./testrwx.sh
你想测试哪个文件?c/thread.c
结果:
3、测试字符串str1是否为空,为空则返回0
命令:str1=""
test -z "$str1"
echo $?
结果:
4、测试字符串str1是否为空,非空则返回0,为空返回非0
命令:test -n "$str1"
echo $?
结果:
5、比较str1与str2是否相同,相同则返回0,否则返回非0
命令:[ "$str1" = "$str2" ]
echo $?
结果:
6、比较str1与str2是否不同,不同则返回0
命令:[ "$str1" != "$str2" ]
echo $?
结果:
7、比较str1与str2的大小
命令:[ "$str1" \> "$str2" ]
echo $?
结果:
8、建立文件comint.sh,进行整数比较
脚本:
#!/bin/sh
a=10
b=20
if [ $a -eq $b ]
then
echo "$a -eq $b : a is equal to b"
else
echo "$a -eq $b: a is not equal to b"
fi
if [ $a -ne $b ]
then
echo "$a -ne $b: a is not equal to b"
else
echo "$a -ne $b : a is equal to b"
fi
if [ $a -gt $b ]
then
echo "$a -gt $b: a is greater than b"
else
echo "$a -gt $b: a is not greater than b"
fi
if [ $a -lt $b ]
then
echo "$a -lt $b: a is less than b"
else
echo "$a -lt $b: a is not less than b"
fi
if [ $a -ge $b ]
then
echo "$a -ge $b: a is greater or equal to b"
else
echo "$a -ge $b: a is not greater or equal to b"
fi
if [ $a -le $b ]
then
echo "$a -le $b: a is less or equal to b"
else
echo "$a -le $b: a is not less or equal to b"
fi
命令:. ./comint.sh
结果:
9、建立文件log.sh,进行逻辑运算
脚本:
#!bin/sh
iv=15
if [ ! "$iv" -lt 5 -o "$iv" -gt 30 ];then
echo "$iv不小于5或大于30"
fi
if [ "$iv" -lt 20 -a "$iv" -gt 10 ];then
echo "$iv小于20且大于10"
fi
命令:. ./log.sh
结果:
10、建立文件score.sh,使用if进行成绩等级的判断
脚本:
#!/bin/bash
echo -n "请输入一个分数:"
read score
if [ "$score" -lt 60 ];then
echo "$score分属于不及格"
fi
if [ "$score" -lt 70 -a "$score" -ge 60 ];then
echo "$score分属于及格"
fi
if [ "$score" -lt 80 -a "$score" -ge 70 ];then
echo "$score分属于中等"
fi
if [ "$score" -lt 90 -a "$score" -ge 80 ];then
echo "$score分属于良好"
fi
if [ "$score" -le 100 -a "$score" -ge 90 ];then
echo "$score分属于优秀"
fi
命令:. ./score.sh
请输入一个分数:93
结果:
11、建立文件check_file.sh,判断某个文件是否存在
脚本:
#!/bin/bash
echo -n "请输入一个文件名及路径:"
read FILE
if [ -e $FILE ];then
echo "$FILE存在"
else
echo "$FILE不存在"
fi
命令:. ./check_file.sh
结果:
12、建立文件ifelif.sh,对成绩等级进行判断
脚本:
#!/bin/bash
echo -n "请输入一个分数:"
read score
if [ "$score" -lt 60 ];then
echo "$score分属于不及格"
elif [ "$score" -lt 70 -a "$score" -ge 60 ];then
echo "$score分属于及格"
elif [ "$score" -lt 80 -a "$score" -ge 70 ];then
echo "$score分属于中等"
elif [ "$score" -lt 90 -a "$score" -ge 80 ];then
echo "$score分属于良好"
else echo "$score分属于优秀"
fi
命令:. ./ifelif.sh
结果: