文件目录属性判断
if特殊用法
cace判断
for循环
文件目录属性判断
[ -f file ]判断是否是普通文件,且存在
#!/bin/bash
f="/tmp/jerrylinux"
fi [-f $f ]
then
echo $f exist
else
touch $f
fi
[ -d file ] 判断是否是目录,且存在
#!/bin/bash
f="/tmp/jerrylinux"
fi [ -d $f ]
then
echo $f exist
else
touch $f
fi
[ -e file ] 判断文件或目录是否存在
#!/bin/bash
f="/tmp/jerrylinux"
fi [ -e $f ]
then
echo $f exist
else
touch $f
fi
[ -r file ] 判断文件是否可读
#!/bin/bash
f="/tmp/jerrylinux"
fi [ -r $f ]
then
echo $f readable
fi
[ -w file ] 判断文件是否可写
#!/bin/bash
f="/tmp/jerrylinux"
fi [ -w $f ]
then
echo $f writable
fi
[ -x file ] 判断文件是否可执行
#!/bin/bash
f="/tmp/jerrylinux"
fi [ -x $f ]
then
echo $f executable
fi
如果文件存在,则删除
#!/bin/bash
f="/tmp/jerrylinux"
fi [ -f $f ]
then
rm -f $f
fi
#!/bin/bash
f="/tmp/jerrylinux"
[ -f $f ] && rm -f $f
如果文件不存在,执行后面的命令
#!/bin/bash
f="/tmp/jerrylinux"
[ -f $f ] || touch $f
#!/bin/bash
f="/tmp/jerrylinux"
if [ ! -f $f ]
then
touch $f
fi
if特殊用法
if [ -z "$a" ] 这个表示当变量a的值为空时会怎么样
#!/bin/bash
n=’wc -l /tmp/test‘
if [ -z "$n" ]
then
echo error
exit
elif [ $n -gt 100 ]
then
echo aldkfjsk
fi
if [ -n "$a" ] 表示当变量a的值不为空
-n 判断变量的时候,需要用""双引号引起来,若是文件的时候,则不需要用双引号引起来
[root@ying01 shell]# if [ -n file3.sh ]; then echo ok; fi
ok
[root@ying01 shell]# if [ -n "$b" ]; then echo $b; else echo "b is null"; fi
b is null
if grep -q '123' 1.txt; then 表示如果1.txt中含有'123'的行时会怎么样 -q 仅仅过滤,不显示内容
if [ ! -e file ]; then 表示文件不存在时会怎么样
if (($a<1)); then …等同于 if [ $a -lt 1 ]; then…
[ ] 中不能使用<,>,==,!=,>=,<=这样的符号
cace判断
格式
case 变量名 in
value1)
command
;;
value2)
command
;;
*)
commond
;;
esac
在case程序中,可以在条件中使用|,表示或的意思, 比如
2|3)
command
;;
案例:
#!/bin/bash
read -p "Please input a number: " n
if [ -z "$n" ]
then
echo "Please input a number."
exit 1
fi
n1=`echo $n|sed 's/[0-9]//g'` 查找替换
if [ -n "$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
echo "not ok"
;;
echo "ok"
;;
echo "ook"
;;
echo "oook"
;;
*)
echo "The number range is 0-100."
;;
esac
for循环
语法:for 变量名 in 条件; do …; done
案例1
#!/bin/bash
sum=0
for i in `seq 1 100`
do
sum=$[$sum+$i]
echo $i
done
echo $sum
文件列表循环
#!/bin/bash
cd /etc/
for a in `ls /etc/`
do
if [ -d $a ]
then
ls -d $a
fi
done
for 循环是会以空格或回车作为分隔符