DAY7
文件目录属性判断
[ -f file ]判断是否是普通文件,且存在
[ -d file ] 判断是否是目录,且存在
[ -e file ] 判断文件或目录是否存在
[ -r file ] 判断文件是否可读
[ -w file ] 判断文件是否可写
[ -x file ] 判断文件是否可执行
[ -f file ]判断是否是普通文件,且存在
判断是否是目录,且存在
判断文件或目录是否存在
[ -r file ] 判断文件是否可读
[ -w file ] 判断文件是否可写
[ -x file ] 判断文件是否可执行
并且&& 前一条命令执行成功才会继续执行之后的命令
或者 || 前面命令不成功时,执行后面的命令
if特殊用法
if [ -z “a” ] 表示当变量a的值不为空
if grep -q ‘123’ 1.txt; then 表示如果1.txt中含有’123’的行时会怎么样
if [ ! -e file ]; then 表示文件不存在时会怎么样
if (($a<1)); then …等同于 if [ $a -lt 1 ]; then…
[ ] 中不能使用<,>,==,!=,>=,<=这样的符号
-z 表示变量为空
-n表示变量不为空
if grep -q ‘123’ 1.txt; then 表示如果1.txt中含有’123’的行时会怎么样
if [ ! -e file ]; then 表示文件不存在时会怎么样
if (($a<1)); then …等同于 if [ $a -lt 1 ]; then…
[ ] 中不能使用<,>,==,!=,>=,<=这样的符号
case判断
case格式
变量名 in
value1)
command
;;
value2)
command
;;
*)
commond
;;
esac
在case程序中,可以在条件中使用|,表示或的意思, 比如
2|3)
command
;;
脚本案例
目的:用户输入一个数字,然后用脚本去判断这个数字的范围
#!/bin/bash
read -p "Please input a number: " n
#read 让用户输出一些字符串;赋值给最后一个变量;这里的赋值是“n”
if [ -z "$n" ] //变量n 为空
then
echo "Please input a number."
exit 1 //“exit 1”表示执行该部分命令后的返回echo $?的值
fi
n1=`echo $n|sed 's/[0-9]//g'` //确定变量n是否为纯数字,如果是数字,则清空
if [ ! -z "$n1" ]
then
echo "Please input a number."
exit 1
fi
if [ $n -lt 60 ] && [ $n -ge 0 ]
then
tag=1
elif [ $n -ge 60 ] && [ $n -lt 80 ]
then
tag=2
elif [ $n -ge 80 ] && [ $n -lt 90 ]
then
tag=3
elif [ $n -ge 90 ] && [ $n -le 100 ]
then
tag=4
else
tag=0
fi
case $tag in
1)
echo "not ok"
;;
2)
echo "ok"
;;
3)
echo "ook"
;;
4)
echo "oook"
;;
*)
echo "The input value exceeds the calculation range.The number range is 0-100."
;;
esac
for循环
脚本需求:计算出1到100所以数字的和
先打印出1到100数字
#!/bin/bash
for i in seq 1 100
do
echo $i
done
计算出1到100所以数字的和
#!/bin/bash
sum=0
for i in seq 1 100
do
sum=sum+$i]
done
echo $sum
打印出每次计算过程
#!/bin/bash
sum=0
for i in seq 1 100
do
echo "$sum + [i]
echo $sum
done
echo $sum
需求:ls出etc下的所有目录子目录
#!/bin/bash
cd /etc/
for a in ls /etc/
do
if [ -d $a ]
then
echo $a
ls $a
fi
done
for循环对象会以空格或者回车符号作为分隔符