gpt4 book ai didi

linux - 如何检查BASH中的文件?

转载 作者:行者123 更新时间:2023-12-03 09:59:34 25 4
gpt4 key购买 nike

我正在为学校写BASH。 Shell脚本应搜索任何名为'file'的文本文件,文件末尾的数字应为1-10。程序回显说每个文件是否存在。

但是,我只是无法让该程序搜索文件。

我做了一个递增一的数字。我找不到将此变量放在"file"和“.txt”之间的方法。我能做些什么?

#!/bin/sh
number=1
x=$(grep file<$number>.txt)
((number++))
while [ $number -le 10 ]
do
if [ $x -eq true ]
then
echo file<$number>.txt exists
else
echo file<$number>.txt does not exist
fi
((number++))
done

最佳答案

使用bash:

$ touch file3.txt
$ for i in {1..10}; do file="file${i}.txt"; [[ -f $file ]] && echo "$file exists" || echo "$file doesn't exist"; done
file1.txt doesn't exist
file2.txt doesn't exist
file3.txt exists
file4.txt doesn't exist
file5.txt doesn't exist
file6.txt doesn't exist
file7.txt doesn't exist
file8.txt doesn't exist
file9.txt doesn't exist
file10.txt doesn't exist

使用 sh:
$ for i in `seq 1 10`; do file="file${i}.txt"; if [ -f "$file" ]; then echo "$file exists"; else echo "$file doesn't exist"; fi; done
file1.txt doesn't exist
file2.txt doesn't exist
file3.txt exists
file4.txt doesn't exist
file5.txt doesn't exist
file6.txt doesn't exist
file7.txt doesn't exist
file8.txt doesn't exist
file9.txt doesn't exist
file10.txt doesn't exist

关于linux - 如何检查BASH中的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49761673/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com