编辑shell脚本,查找当前文件夹,文件名以字母“x”开头的文件是否存在。如果存在给出提示,如果不存在则建立文件名为x_mm.sh的文件
要求:给出完整的shell设计
#! /bin/bash
# find 命令 查找类型为文件并且文件名字以x开头,如果不循环子目录查找可以加"-maxdepth 1"表示只在当前层级
# wc 命令 统计输出的条数
count=$(find . -type f -name "x*" | wc -l)
# 如果条数大于0表示文件存在
if [[ $count -gt 0 ]]; then
echo 'file with x start exist!'
else
echo 'file not exist create'
touch x_mm.sh
fi
#!/bin/bash
# 通过 find 命令查找文件名以x开头的文件,-maxdepth 1表示只查一层
# 如果想嵌套查询目录下所有文件,可以将 -maxdepth 1 去掉
file=`find . -maxdepth 1 -type f -exec basename {} \;| grep "^x"`
# 判断file是否为空
if [ -n "$file" ]; then
echo "文件存在:"$file
else
echo "文件不存在,创建文件x_mm.sh"
touch x_mm.sh
fi
#shell判断文件夹是否存在
#如果文件夹不存在,创建文件夹
if [ ! -d "/Top" ]; then
mkdir -p /Topfi
#shell判断文件,目录是否存在或者具有权限
folder="/Top"
file="/Top/test.txt"
# -x 参数判断 $folder 是否存在并且是否具有可执行权限
if [ ! -x "$folder"]; then
mkdir "$folder"
fi
# -d 参数判断 $folder 是否存在
if [ ! -d "$folder"]; then
mkdir "$folder"
fi
# -f 参数判断 $file 是否存在
if [ ! -f "$file" ]; then
touch "$file"
fi
# -n 判断一个"变量"是否有值
if [ ! -n "$file" ]; then
echo "$file 变量为空!"
exit 0
fi
# 判断两个变量的字符串内容是否相同
if [ "$file1" = "$file2" ]; then
echo "$file1 equal $file2"
else
echo "$file1 not equal $file2"
fi
先看效果
具体代码如下
#!/bin/bash
# get current dir
a=`pwd`;
count=`ls $a | grep -E ^"x" | wc -l`;
if [ $count -gt 0 ]
then
echo "current dir contain file that start with x";
else
touch x_mm.sh;
fi
#shell判断文件夹是否存在
#如果文件夹不存在,创建文件夹
if [ ! -d "/Top" ]; then
mkdir -p /Topfi
#shell判断文件,目录是否存在或者具有权限
folder="/Top"
file="/Top/test.txt"
# -x 参数判断 $folder 是否存在并且是否具有可执行权限
if [ ! -x "$folder"]; then
mkdir "$folder"
fi
# -d 参数判断 $folder 是否存在
if [ ! -d "$folder"]; then
mkdir "$folder"
fi
# -f 参数判断 $file 是否存在
if [ ! -f "$file" ]; then
touch "$file"
fi
# -n 判断一个"变量"是否有值
if [ ! -n "$file" ]; then
echo "$file 变量为空!"
exit 0
fi
# 判断两个变量的字符串内容是否相同
if [ "$file1" = "$file2" ]; then
echo "$file1 equal $file2"
else
echo "$file1 not equal $file2"
fi
只需要查当前一层目录就行了,还是说需要嵌套查询?
#!/bin/bash
exist=0
items=$(ls -l ./)
for item in items; do
if [ -f item]; then
if [[ ${item:0:1} -eq "x" ]]; then
exist=1
break
fi
fi
done
if [[ exist = 1 ]]; then
echo "file exists"
else
touch x_mn.sh
fi
大概是这意思。
题主参考下这个链接
https://b23.tv/GWr6jJy
真的是青菜萝卜,各有所爱了,
不过题主真的可以参考不同的写法,看看哪种适合自己了。
#! /bin/bash
count=$(find . -type f -name "x*" | wc -l)
# 如果条数大于0表示文件存在
if [[ $count -gt 0 ]]; then
echo 'file with x start exist!'
else
echo 'file not exist create'
touch x_mm.sh
fi
遍历,判断,写的各种觉得没什么问题