[英]Exiting a shell script from inside a while loop
我正在写一个简单的shell脚本,如果在文件中找到输入字符串,则应该以0退出,如果不是,则退出1
INPSTR=$1
cat ~/file.txt | while read line
do
if [[ $line == *$INPSTR* ]]; then
exit 0
fi
done
#string not found
exit 1
实际发生的是当找到字符串时,循环退出,然后shell进入“退出1”。 在循环中完全退出shell脚本的正确方法是什么?
您需要避免在管道中创建子shell,避免使用管道和不必要的cat
:
INPSTR="$1"
while read -r line
do
if [[ $line == *"$INPSTR"* ]]; then
exit 0
fi
done < ~/file.txt
#string not found
exit 1
否则, exit 0
仅退出由管道创建的子shell,稍后当循环结束时,则从父shell使用exit 1
。
你可以使用$捕获子shell的返回码吗? 像这样
INPSTR=$1
cat ~/file.txt | while read line
do
if [[ $line == *$INPSTR* ]]; then
exit 0
fi
done
if [[ $? -eq 0 ]]; then
exit 0
else
#string not found
exit 1
fi
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.