gpt4 book ai didi

Bash "for"循环,如果条件计数为零?

转载 作者:行者123 更新时间:2023-12-05 09:24:52 26 4
gpt4 key购买 nike

我在 bash 中有一个 for 循环;

for Names in `grep "name" $people`
do
echo "name is $name"
done

我怎样才能有一个 if 语句来表达类似的内容;

for Name in `grep "name" $people`
# Make sure we found some names
if [ "count of $Name=0" ]
then
echo "no names found"
fi

# Else, if we did grep out a list of names, print them
do
echo "name is $Name"
done

最佳答案

添加 compound conditional test (&&)如果 for block 的返回码为 0(意味着它从未进入循环并调用了 false),则打印调试文本:

for NAME in $(grep "name" $people)
do
echo "Name is ${NAME}"
false
done && echo "no names found"

如果您不喜欢它的读法,只需将 for: 反转即可:

! for NAME in $(grep "name" $people)
do
echo "Name is ${NAME}"
false
done || echo "no names found"

关于Bash "for"循环,如果条件计数为零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8214865/

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