复合表达式的 bash 优先级

标签 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

为什么“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/

相关文章:

python - 如何将带有空格的字符串作为单个值从 Python 发送到 Bash 子进程?

bash - 除了空头期权之外,为什么我还应该提供多头期权?

linux - 用适当数量的 "*"替换偶数词

bash - firebase 工具 "-bash: firebase: command not found"

bash - 从 Vim 中执行 Bash 函数 - 我该怎么做?

bash - 将 .zsh_history 文件转换为 .bash_history 文件

bash - 如何检查 bash for 循环中的不平等?

linux - 在 Linux 上,为什么 'echo' 不能使用 ANSI 颜色代码而 'print' 可以?

java - 在java中创建一个运行文件

bash - 在shell的一行中运行多个命令