您的位置:首页 > 运维架构 > Shell

SHELL实战_day7

2018-12-25 22:35 573 查看
一   if 判断文件、目录属性

[ -f file ]判断是否是普通文件,且存在
[ -d file ] 判断是否是目录,且存在
[ -e file ] 判断文件或目录是否存在
[ -r file ] 判断文件是否可读
[ -w file ] 判断文件是否可写
[ -x file ] 判断文件是否可执行

二   if判断的一些特殊用法

if [ -z "$n"]示当变量a的值为空时会怎么样
if [ -n "$a" ] 表示当变量a的值不为空
if grep -q '123' 1.txt; then  表示如果1.txt中含有'123'的行时会怎么样
grep -w :表示一个单词
grep -q: 过滤出来的内容不显示在屏幕上

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
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
1)
echo "not ok"
;;
2)
echo "ok"
;;
3)
echo "ook"
;;
4)
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

案例2
文件列表循环
#!/bin/bash
cd /etc/
for a in

ls /etc/

do
    if [ -d $a ]
    then
       ls -d $a
    fi
done

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  if cas for