如何检查BASH中的文件?

时间:2018-04-10 19:37:51

标签: linux bash shell

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

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

我做了一个增加1的数字。我找不到把这个变量放在'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

1 个答案:

答案 0 :(得分:1)

使用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