shell训练计划30天之第七天

一、if判断文件、目录属性

[ -f file ] 判断是否是普通文件,且存在

#!/bin/bash f="/tmp/aminglinux" if [ -f $f ] then echo $f exist else touch $f fi

[ -d file ] 判断是否是目录,且存在

#!/bin/bash f="/tmp/aminglinux" if [ -d $f ] then echo $f exist else touch $f fi

[ -e file ] 判断文件或目录是否存在

#!/bin/bash f="/tmp/aminglinux" if [ -e $f ] then echo $f exist else touch $f fi

[ -r file ] 判断文件是否可读

#!/bin/bash f="/tmp/aminglinux" if [ -e $f ] then echo $f readable fi

[ -w file ] 判断文件是否可写

#!/bin/bash f="/tmp/aminglinux" if [ -e $f ] then echo $f writeable fi

[ -x file ] 判断文件是否可执行

#!/bin/bash f="/tmp/aminglinux" if [ -e $f ] then echo $f exeable fi

脚本改良

#!/bin/bash

f=" /tmp/aminglinux"

[ -f $f] && rm -f $f

等同于

if [ -f $f ]

then

rm -f $f

fi

&& 如果判断条件成立则执行

|| 如果判断条件不成立则执行

[ ! -f $f] && rm -f $f 加感叹号表示取反,判断文件是否不存在

二、if的一些特殊用法

if [ -z "$a" ] 表示当变量a的值为空时,做什么处理

if [ -n "$a"] 表示当变量a的值不为空

if ! grep -wq 'user1' /etc/passwd;then useradd user1 ; fi 判断是否存在user1用户,如

果不存在就创建

使用-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

[]中不能使用<,>,==,!=,>=,<=这类的符号

脚本中变量需要使用双引号,文件不需要双引号

grep -wq 过滤单词并不打印出来

-w过滤单词

-q 不打印过滤的 内容

三、case判断

在 case中可以使用或即|

1.格式

value1)

command

;;

value2)

command

;;

*)

command

;;

ease

 

2.例子

#!/bin/bash

read -p "Please input a number :" n 等待用户输入 read -p

if [ -z $n ] 检测变量是否为空,即用户是否输入内容

then

echo "Pleas input a number." 当变量为空时输出

exit 1

fi

n1=`echo $n|sed 's/[0-9]//g'` 使用sed清空$n中的数字

if [ ! -z $n1 ] 若变量为不空则输出提示,证明用户输入了除了

数字以外的内容

the

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 100]

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 "ok ok"

;;

4)

echo " oook"

;;

*)

echo "The number range is 0-100"

四、for循环

1.语法:for 变量名 in 条件 ; do 。。。;done

2.例子

#!/bin/bash

sum=0

for i in `seq 1 100`

do

sum=$[$sum+$i]

echo $i

done

echo $sun

 

#!/bin/bash

cd /etc/

for a in `ls /etc/`

do

if [ -d $a ]

then

echo $a

ls $a

fi

done

 

for i in `seq 1 3` ; do echo $i ;done

for i in `ls ./` ; do echo $1 ;done

for循环的时候会以空格或者回车为分隔符,要特别注意

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值