2

我想浏览一个文件列表并检查它们是否存在,如果文件不存在则给出错误并退出。我写了以下代码:

FILES=( file1.txt file2.txt file3.txt )

for file in ${FILES[@]}; do
        [ -e "${file}" ] || ( echo "ERROR: ${file} does not exist" >&2 && exit )
done

它运行没有错误,并产生以下内容(如果不存在任何文件):

ERROR: file1.txt does not exist
ERROR: file2.txt does not exist
ERROR: file3.txt does not exist

为什么“退出”从未执行?此外,我想知道做我想做的事情的首选方法(用括号控制分组)。

4

1 回答 1

5

可能是因为您( echo "ERROR: ${file} does not exist" >&2 && exit )作为子进程运行(您的命令在 () 内部)?因此,您正在退出子流程。这是你的 shell 脚本的痕迹(我用 得到它set -x):

+ FILES=(file1.txt file2.txt file3.txt)
+ for file in '${FILES[@]}'
+ '[' -e file1.txt ']'
+ echo 'ERROR: file1.txt does not exist'
ERROR: file1.txt does not exist
+ exit
+ for file in '${FILES[@]}'
+ '[' -e file2.txt ']'
+ echo 'ERROR: file2.txt does not exist'
ERROR: file2.txt does not exist
+ exit
+ for file in '${FILES[@]}'
+ '[' -e file3.txt ']'
+ echo 'ERROR: file3.txt does not exist'
ERROR: file3.txt does not exist
+ exit

这有效:

set -x
FILES=( file1.txt file2.txt file3.txt )

for file in ${FILES[@]}; do
        [ -e "${file}" ] || echo "ERROR: ${file} does not exist" >&2 && exit
done

放入set -x你的文件,看看你自己。

或者像这样

set -x
FILES=( file1.txt file2.txt file3.txt )

for file in ${FILES[@]}; do
        [ -e "${file}" ] || (echo "ERROR: ${file} does not exist" >&2) && exit
done

更新
我猜你在问bash - 分组命令

这是在同一进程中分组和执行

FILES=( file1.txt file2.txt file3.txt )

for file in ${FILES[@]}; do
        [ -e "${file}" ] || { echo "ERROR: ${file} does not exist" >&2; exit; }
done

这是在子流程中分组和执行

FILES=( file1.txt file2.txt file3.txt )

for file in ${FILES[@]}; do
        [ -e "${file}" ] || ( echo "ERROR: ${file} does not exist" >&2; exit )
done
于 2013-03-05T13:01:05.447 回答