shell脚本:编辑file_check.sh脚本检测文件是否存在

1.要求

脚本在执行时

1)如果脚本后未指定代检测文件名时报错“未指定检测文件,请指定”

2)如果脚本后指定的代检测文件不存在时报错“此文件不存在”

3)当文件存在时请检测文件类型并显示到输出中

2.思路

输入文件名时最基本的要求,如果未输入文件名直接报错进退出

所以

[root@westos_ansible mnt]# vim file_check.sh 
[root@westos_ansible mnt]# cat file_check.sh 
#!/bin/bash
[ -z "$1" ] && {
  echo "Error: Please input filename following script"
  exit
}
[root@westos_ansible mnt]# sh file_check.sh 
Error: Please input filename following script

输入了不存在的文件名时检测:

[root@westos_ansible mnt]# vim file_check.sh 
[root@westos_ansible mnt]# cat file_check.sh 
#!/bin/bash
[ -z "$1" ] && {
  echo "Error: Please input filename following script !!"
  exit
}

[ ! -e "$1" ] && {
  echo "Error: $1 is not exist !!"
  exit
}
[root@westos_ansible mnt]# sh file_check.sh hahaha
Error: hahaha is not exist !!

其中 ! 表示条件反选

输入正确文件名并执行脚本时

显示

[root@westos_ansible mnt]# sh file_check.sh /mnt/
/mnt/ is directory
[root@westos_ansible mnt]# sh file_check.sh /etc/passwd
/etc/passwd is commom file

3.脚本代码

#!/bin/bash
[ -z "$1" ] && {
  echo "Error: Please input filename following script !!"
  exit
}

[ ! -e "$1" ] && {
  echo "Error: $1 is not exist !!"
  exit
}

[ -L "$1" ] && {
  echo "$1 is link file"
  exit
}

[ -f "$1" ] && {
  echo "$1 is commom file"
  exit
}

[ -d "$1" ] && {
  echo "$1 is directory"
  exit
}

[ -b "$1" ] && {
  echo "$1 is blcok device file"
  exit
}

[ -S "$1" ] && {
  echo "$1 is socket"
  exit
}

[ -c "$1" ] && {
  echo "$1 is char"
  exit
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值