我想查看文件列表并检查它们是否存在,如果文件不存在则发出错误并退出。我写了以下代码:
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
为什么“退出”从未执行过?另外,我想知道我正在尝试做的事情的首选方式(用括号控制分组)。
答案 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