本文介绍了如何检查Bash中是否存在某些文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 bash 脚本中,我必须检查是否存在多个文件。

In a bash script, I have to check for the existence of several files.

我知道这样做很尴尬,如下所示,但这意味着我的主程序必须位于该丑陋的嵌套结构内:

I know an awkward way to do it, which is as follows, but that would mean that my main program has to be within that ugly nested structure:

if [ -f $FILE1 ]
then
if [ -f $FILE2 ]
then
  echo OK
  # MAIN PROGRAM HERE
fi
fi

以下版本不起作用:

([ -f $FILE1 ] && [ -f $FILE2 ]) ||  ( echo "NOT FOUND"; exit 1 )
echo OK

打印

NOT FOUND
OK

是否有一种优雅的方法来做到这一点?

Is there an elegant way to do this right?

更新:查看已接受的答案。另外,在优雅方面,我喜欢:

UPDATE: See the accepted answer. In addition, in terms of elegance I like Jonathan Leffler's answer:

arg0=$(basename $0 .sh)
error()
{
    echo "$arg0: $@" 1>&2
    exit 1
}

[ -f $FILE2 ] || error "$FILE2 not found"
[ -f $FILE1 ] || error "$FILE1 not found"


推荐答案

怎么样

if [[ ! ( -f $FILE1 && -f $FILE2 ) ]]; then
    echo NOT FOUND
    exit 1
fi

# do stuff
echo OK

请参见 help [[和 help test [[样式测试可用的选项。另请阅读。

See help [[ and help test for the options usable with the [[ style tests. Also read this faq entry.

您的版本不起作用,因为(...)会生成一个新的子shell,在其中执行 exit 。因此,它仅影响该子shell,而不影响执行脚本。

Your version does not work because (...) spawns a new sub-shell, in which the exit is executed. It therefor only affects that subshell, but not the executing script.

下面的方法代替了,在 {...}之间执行命令。 code>在当前shell中。

The following works instead, executing the commands between {...} in the current shell.

我还应该注意,您必须引用两个变量,以确保不会发生不必要的扩展或单词拆分(它们必须作为一个参数传递给 [)。

I should also note that you have to quote both variables to ensure there is no unwanted expansion or word splitting made (they have to be passed as one argument to [).

[ -f "$FILE1" ] && [ -f "$FILE2" ] || { echo "NOT FOUND"; exit 1; }

这篇关于如何检查Bash中是否存在某些文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 09:29