linux下利用test命令的判断文件属性的功能编写一个shell脚本
发布网友
发布时间:2022-04-23 13:56
我来回答
共2个回答
热心网友
时间:2023-01-21 22:22
对于文件是否有读写权限,这个没有涉及
#!/bin/bash
read -p "please input the file name:" file
if [ ! -n "$file" ];
then
echo please input the file name please
exit 0
fi
ls $file > /dev/null 2>&1
if [ $? -eq 0 ]
then
echo file exist
cp $file $file.bak
vi $file
else
echo file not exist!
fi追问你好,可否再补充一下呢关于权限的呢 。
我记得ll -l 文件名,可以查看相关权限,能否提取出来匹配“r”“w"再给予echo提示呢。
劳烦了,谢谢
另外能否用test命令完善下,感谢...
追答那就加一个简单的判断
#!/bin/bash
read -p "please input the file name:" file
if [ ! -n "$file" ];
then
echo please input the file name please
exit 0
fi
ls $file > /dev/null 2>&1
if [ $? -eq 0 ]
then
echo file exist
ls -l $file | awk '{print $1}' |grep rw > /dev/null 2>&1
if [ $? -eq 0 ]
then
echo file has read/write right
cp $file $file.bak
vi $file
else
echo file donot have read/write right
fi
else
echo file not exist!
fi
热心网友
时间:2023-01-21 23:40
#!/bin/bash
#
backupdir="/tmp"
while true;do
read -p "Input a file.[{q or quit}exit]:" file
case $file in
q|quit)
exit 0
;;
*)
test -z "$file" && echo "Parameter is not allowed to be empty." && continue
test ! -e "$file" && echo "$file is not exist." && continue
test -d "$file" && echo "Can not vi $file." && continue
test ! -r $file && echo "Can't read $file." && continue
test -r "$file" -a ! -d "$file" && cp -af "$file" $backupdir/`basename $file`.backup && vi $file
;;
esac
done