gpt4 book ai didi

linux - Bash 脚本条件

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:03:51 25 4
gpt4 key购买 nike

我正在构建一个 bash 脚本来根据上一个命令发送电子邮件。我似乎遇到了困难。在脚本之外,该命令工作正常,但将其放入脚本时,它不会给出预期的结果。

这是脚本片段:

grep -vFxf /path/to/first/file /path/to/second/file > /path/to/output/file.txt 
if [ -s file.txt ] || echo "file is empty";
then
swaks -t "1@email.com" -f "norply@email.com" --header "Subject: sample" --body "Empty"
else
swaks -t "1@email.com" -f "norply@email.com" --header "subject: sample" --body "Not Empty"
fi

我在脚本外运行了命令,我可以看到有数据,但是当我在脚本内添加命令时,我得到的是空输出。请指教 。提前谢谢你。

最佳答案

您的条件将始终为真,因为如果 [ -s file.txt ] 失败,|| 列表的退出状态就是 echo,几乎可以保证为 0。您想将 echo 从条件中移出并移到 if 语句的主体中。 (为了进一步简化,只需将主体设置为一个变量并在 if 完成后调用 swaks

if [ -s file.txt ];
then
body="Not Empty"
else
echo "file is empty"
body="Empty"
fi
swaks -t "1@email.com" -f "norply@email.com" --header "subject: sample" --body "$body"

如果你创建 file.txt 的唯一原因是检查它是否为空,你可以直接将 grep 命令放在 if 条件:

if grep -vFxfq /atph/to/first/file /path/to/second/file; then
body="Not Empty"
else
echo "No output"
body="Empty"
fi

swaks -t "1@email.com" -f "norply@email.com" --header "subject: sample" --body "$body"

关于linux - Bash 脚本条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49500201/

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