我想浏览文件列表并检查它们是否存在,如果文件不存在则给出错误并退出。我编写了以下代码:
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
为什么“exit”从未被执行?此外,我想知道做我想做的事情的首选方法(用括号控制分组)。
最佳答案
可能是因为您运行 ( echo "ERROR: ${file} does not 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 - 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
关于复合表达式的 bash 优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15224354/