gpt4 book ai didi

linux - Bash 脚本对于不同的结果获得相同的存在状态

转载 作者:太空宇宙 更新时间:2023-11-04 05:09:46 24 4
gpt4 key购买 nike

我的脚本查找文件,grep 模式,如果匹配,则将文件复制到目标文件夹。正如你所看到的,我使用管道来做到这一点。整个命令工作正常,但我无法测试它,因为无论是否找到文件,我都会得到相同的退出状态。为了说明这一点,下面我举两个例子。首先,我找到了该文件并 grep 该文件。请注意打印的退出状态。在第二个示例中,我没有找到并 grep 该文件,但退出状态是相同的。我该怎么做才能正确测试这个命令?

  1. 文件存在。

    find $HOME -type f -name arq_*.txt | xargs -n1 -I{} grep -l 00819047 {}  | xargs -n1 -I{} cp -v {} $HOME/aka 

    `/home/fabrifb/arq_144.txt' -> `/home/fabrifb/aka/arq_144.txt'

    echo "0)${PIPESTATUS[0]} 1)${PIPESTATUS [1]} : 2)${PIPWSTATUS[2]} ?)$? @)${PIPESTATUS[@]}"

    结果:

    0)0 1)0 : 2) ?)0 @)0 0 0
  2. 不存在

    find $HOME -type f -name arqX_*.txt | xargs -n1 -I{} grep -l X00819047 {}  | xargs -n1 -I{} cp -v {} $HOME/aka

    echo "0)${PIPESTATUS[0]} 1)${PIPESTATUS [1]} : 2)${PIPWSTATUS[2]} ?)$? @)${PIPESTATUS[@]}"

    结果

    0)0 1)0 : 2) ?)0 @)0 0 0

我希望能够区分这两种情况,以便在文件不存在时警告用户。

最佳答案

如果没有找到任何文件,

find 将返回零。 grep 返回 1,但它永远不会接收任何文件名,因为它被包装在 xargs 中,对于空输入,它再次返回 0。如果你想检查文件是否存在,你可以使用数组:

shopt -s nullglob
files=(arq_*.txt)
if [[ "${#files[@]}" -eq 0 ]]
then
[handle non-existing files]
fi
for file in "${files[@]}"
do
if grep 00819047 "$file"
then
cp "$file" $HOME/aka
fi
done

或保护变量:

found=0
for file in arg_*.txt
do
found=1
[loop contents like above]
done
if [[ "$found" -eq 0 ]]
then
[handle non-existing files]
fi

您还有一个拼写错误PIPWSTATUS。但无论如何,您只需打印 ${PIPESTATUS[@]}" 即可获取该数组的完整内容。

关于linux - Bash 脚本对于不同的结果获得相同的存在状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56917605/

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