简体   繁体   English

Shell脚本-检查文件是否存在

[英]Shell Scripting - checking for file existence

I'm trying to write a shell script that checks if 3 specific files exist in the folder. 我正在尝试编写一个Shell脚本来检查文件夹中是否存在3个特定文件。 I also want to store the results in an array. 我也想将结果存储在数组中。 Once the file checking is done, I want to check the array to make sure at least one (1) file exists before the script can continue. 文件检查完成后,我想检查数组以确保至少有一个(1)文件存在,然后脚本才能继续。

A successful output should look like this: 成功的输出应如下所示:

File file1.sh..........OK!
File file2.sh..........NOT FOUND!
File file3.sh..........OK!
File check completed successfully.

A failed output should look like this: 输出失败应如下所示:

File file1.sh..........NOT FOUND!
File file2.sh..........NOT FOUND!
File file3.sh..........NOT FOUND!
At least one file is required to continue.

Right now I am using if/else statements like this: 现在我正在使用这样的if / else语句:

#!/bin/bash
if [[ -f file1.sh ]]; then
  echo "File file1.sh........OK!";
  isFILE1=1
else 
  echo "File file1.sh........NOT FOUND!";
  isFILE1=0
fi

However, I'd like to do something like this instead. 但是,我想做这样的事情。 And also make printing the result on the same line as the File file1.sh.......: 并在文件File1.sh .......的同一行上打印结果:

#!/bin/bash
echo "File file1.sh.........";
if [[ -f file1.sh ]]; then
  echo "OK!";
  isFile[0]=1;
else 
  echo "NOT FOUND!";
  isFile[0]=0;
fi

I'm not sure how to check if at least 1 file in the array isFile exists. 我不确定如何检查数组isFile中是否至少存在1个文件。

To keep the output on one line change this 为了使输出保持一行,请更改此

echo "File file1.sh.........";

to

echo -n "File file1.sh.........";

The -n suppresses the new-line. -n禁止换行。

For checking the file existence from an array, use a singular flag and change it to 1 if you find a file. 要从数组检查文件是否存在,请使用单数标志,如果找到文件,请将其更改为1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM