bash优先级与复合表达式

时间:2013-03-05 12:55:01

标签: bash

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

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

为什么“退出”从未执行过?另外,我想知道我正在尝试做的事情的首选方式(用括号控制分组)。

1 个答案:

答案 0 :(得分:5)

可能因为您运行( echo "ERROR: ${file} does not exist" >&2 && exit )作为子进程(您的命令在inside()中)?所以你要退出子流程。 这是你的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 - grouping Commands

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

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
相关问题