bash - 如何从使用 while 循环的函数返回
问题描述
在我的脚本的主体中,我有以下内容:
while read -p "Enter operand: " first
checkRecall
...
其中checkRecall
定义为:
checkRecall() {
if [ "$next" = MR -a "$times" -ne 0 ]; then
next=$MS
echo "M -> $MS"
elif [ "$first" = MR -a "$times" -eq 0 ]; then
while [ "$first" = MR ] # <-- PROBLEM: exits script when no longer true
do
echo "Nothing in memory"
read -p "Enter a different operand: " first
done
fi
}
times
是在脚本主体中递增的变量。
[ "$first" = MR -a "$times" -eq 0 ]
当条件不再为真时,我试图将控制流返回到脚本的主体。相反,它退出了我的脚本。我如何实现这一目标?
而不是while [ "$first" = MR -a "$times" -eq 0 ]
,我尝试使用以下if/else
语句return
:
while if [ "$first" != MR ]; then
return 1
fi
[ "$first" = MR ]
但这似乎不起作用。
解决方案
我已经完成了主脚本的其余部分,没有看到任何会导致它过早退出的内容。很可能我错过了一些东西,或者我在某个地方有误解,但 FWIW 我现在能够想出一个解决方案:
while [ "$first" = MR ]
do
echo "Nothing in memory"
read -p "Enter a different operand: " first
if [ $first != MR ]; then return
fi
done
推荐阅读
- python-3.x - 如何在 Discord 中发送嵌入到直接消息?
- storybook - 指定 Storybook 的默认页面
- swift - 在 Watchkit 表格行中看不到 Spritekit 场景
- html - Spring boot 请求的映射值变量
- sql - PostgreSQL - 类似的替代品,包含
- reactjs - Wordpress Gutenberg React – 使用 HTML 渲染变量
- reactjs - 如果状态没有变化,则强制重新加载反应 js 组件
- typescript - 为什么这个包装的样式组件错误“没有共同的属性”
- iis -
- 匹配包含字符串的 URL - python - 使用亚洲字符的 FuzzyWuzzy 搜索