用for循环使用数组和if列出文件

我写了一个脚本来检查不同目录中的文件,并希望这个脚本在文件不存在的情况下向我显示错误。 但是由于循环,它显示了ERROR和NO ERROR。 要调整,以便我只能得到错误或无错误的情况下,一个或多个文件丢失或全部存在到他们的目录。

files=("/my/path/to/file1.tar.gz" "/my/path/to/file2.tar.gz") for i in "${files[@]}" do ls -l $i if [ $? -ne 0 ]; then echo "ERROR" else echo "NO ERROR" fi done 

我不能添加退出,如果我将添加,然后下面的脚本的其余部分停止。 ls并不重要。 重要的是检查文件的存在。 它可以是任何方式,如果[-e“/ path / to / file”]等。但是错误很重要,因为如果错误或没有错误,我会发邮件给自己,这就是为什么它的重要性。

你能解释一下,为什么你用'set -e'?

它不工作,因为我想要的。 其逐行打印信息。 但我希望它存储所有信息和打印机错误,如果任何一个丢失或没有错误,如果全部存在。 怎么可能做?

string“错误”是重要的吗? 除此以外:

 set -e for i in "/my/path/to/file1.tar.gz" "/my/path/to/file2.tar.gz" ; do [ -e "$i" ] done 

编辑:

从bash手册:

  -e Exit immediately if a simple command (see SHELL GRAMMAR above) exits with a non-zero status. The shell does not exit if the command that fails is part of the command list immediately following a while or until keyword, part of the test in an if statement, part of a && or || list, or if the command's return value is being inverted via !. A trap on ERR, if set, is executed before the shell exits. 

如果你想打印,我们需要更详细些:

 for i in "/my/path/to/file1.tar.gz" "/my/path/to/file2.tar.gz" ; do [ -e "$i" ] || { echo "ERROR" ; exit 1 ; } done echo "NOERROR" 

如果你想知道循环结束后,那么显而易见的事情就是设置一个variables,指示一切正常。 当某些事情不好的时候,你改变这个variables,在循环结尾查找这个variables,看看有没有什么不好的地方:

 ok=1 for i in "${files[@]}" do if [ ! -e "$i" ]; then ok=0 fi done if [ $ok -eq 1 ]; then echo "NO ERROR" else echo "ERROR" fi 

使用[ ! -e "$i" ] [ ! -e "$i" ]将避免打印ls错误,尽pipe你可以这样做

 ls -l "$i" > /dev/null 2>&1 

ls的输出和错误redirect到/ dev / null

最简单的方法是删除你的else语句,向你的then子句添加一个exit ,并在你的for循环之后回显“NO ERROR”。 (如果你已经完成了for循环,那么所有的文件都存在。)