gpt4 book ai didi

具有复合表达式的 bash 优先级

转载 作者:行者123 更新时间:2023-11-29 09:44:35 28 4
gpt4 key购买 nike

我想遍历文件列表并检查它们是否存在,如果文件不存在则给出错误并退出。我写了下面的代码:

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 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 - 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com