shell条件判断练习

1、编写脚本,测试文件是否存在,不存在则创建

[root@server ~] # cat test1.sh
#!/bin/bash
FILE = $1
echo FILE
if test -e $FILE
then
echo " $FILE 文件已存在 "
else
echo " $FILE 文件不存在,开始新建 ..."
touch $FILE
ls -l $FILE
fi
[root@server ~] # bash temp1.sh /etc/passwd
/etc/passwd
/etc/passwd 文件已存在
[root@server ~] # bash temp1.sh temp
temp
temp 文件不存在,开始新建 ...
-rw-r--r-- 1 root root 0 6 17 14 :53 temp

2、让用户输入一个文件名,并做如下判断:

(1)如果用户输入的文件为空时显示:you must input a filename,并中断程序;

2 )如果用户输入的文件不存在时,显示 the file do not exist ,并中断程序;
3 )如果文件存在,判断该文件的文件类型和执行者对该文件所拥有的的权限。
说明:由于 root 在很多权限的限制上面都是无效的,所以使用 root 执行这个脚本时,常常会发现与 ls -l 的 结果不相同。所以建议使用一般用户来执行这个脚本。
#!/bin/bash
read -p "input a filename:" filename
test -z $filename && echo "you must input a filename" && exit 0
test ! -e $filename && echo "the file $filename do not exist" && exit 0
test -f $filename && filetype = "regulare file"          #filetype是自己定义的变量
[ -L $filename ] && filetype = "link file" || ([ -d $filename ] && filetype = "directory" )
test -r $filename && perm = "readable"          #perm是自己定义的变量
test -w $filename && perm = " $perm writable"                 #变量在原来的基础上添加新内容
test -x $filename && perm = " $perm executable"
echo "the $filename is a $filetype "
echo "and the permissons are: $perm "

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值