Unix脚本无法找到文本文件



我需要这样写一个Unix Shell脚本,如果路径中存在.txt文件,它应该返回0。如果存在其他文件,则应返回1

我试过下面的脚本,但不起作用。。

#!/bin/sh
cd /shz/abc_test/test/test_add/SourceFiles/test1/test01/test02/
chk_files()
{
if [ -e *.txt ]; then
echo "File Exists" 
return 0
exit
else
echo "File doesn't exists" 
return 1
exit
fi
return
}
has_text_files()
{
for f in ./*.txt; do
if [ -f "$f" ]; then
return 0
fi
done
return 1
}

以上代码:

  • 忽略名为*.txt的目录
  • 不打印任何内容,只返回状态
  • 对奇怪的文件名格外小心,例如以-开头或包含空格的文件名
  • 具有更合适的函数名称has_text_files,而不是非特定的chk_files

当然,可以开发更高级的脚本。我看你会用简单的方法。因此,当存在多个文件时,脚本会失败。我更新了功能部分,看起来它正在工作。

chk_files()
{
ifExist=$(ls| grep ".txt$")      # check Files are exist, but no need to list and print.
if [ $? -eq 0 ]; then   # check return code of above command is success (0)
echo "File Exists" 
return 0
else
echo "File doesn't exists" 
return 1
fi
}

最新更新