【问题标题】:bash: set exit status without breaking loop?bash:在不中断循环的情况下设置退出状态?
【发布时间】:2016-03-07 18:15:10
【问题描述】:

我正在编写 bash 脚本来检查 fstab 结构。

for 循环中,我放置了return 语句以在脚本后面使用退出代码,但似乎return 语句在打印第一个请求的输出后打破了循环

如何在不中断循环的情况下分配返回码 1,以便获得所有结果,而不仅仅是第一个?

for i in $(printf  "$child"|awk '/'$new_mounts'/'); do

    chid_count=$(printf  "$child"|awk '/'$new_mounts'/'|wc -l)

    if [[ $chid_count -ge 1 ]]; then
        echo -e "\e[96mfstab order check failed: there are child mounts before parent mount:\e[0m"
        echo -e "\e[31mError: \e[0m "$child"\e[31m  mount point, comes  before \e[0m $mounts \e[31m on fstab\e[0m"
        return 1
    else
        return 0
    fi
done

【问题讨论】:

  • ...btw,'/'$new_mounts'/' 非常非常错误——它将new_mounts 的内容进行字符串拆分,而不是将其作为单个参数的一部分传递给 awk。 "/$new_mounts/" 将是一个改进。考虑通过shellcheck.net 传递您的代码,并仔细阅读mywiki.wooledge.org/Quotes
  • ...类似地,echo -e 在其输出上执行除 print -e 之外的任何操作的任何 shell 都不符合 POSIX sh 标准——请参阅@987654323 处的 POSIX 规范@。考虑改用 printf,它允许使用符合标准的便携式工具来完成类似的任务。
  • 很想标记为 stackoverflow.com/questions/35533501/… 的重复项,但我会重复我在答案中写的内容:使用 Awk。
  • @tripleee,...实际上,对于较大的问题(与直接的语言级别问题相反),非常的准确答案。跨度>
  • @Max_il, ...btw,另外,for i in $(...) 实际上并不是您的目标是迭代输出行时的最佳工具。请参阅 mywiki.wooledge.org/DontReadLinesWithFor 和/或 mywiki.wooledge.org/BashFAQ/001(有关关注最佳实践方法的内容)。

标签: bash


【解决方案1】:

如果您阅读了该语言的文档,立即返回是 应该 做的。这不是 shell 所独有的——我实际上想不出一种具有return 构造的语言不会以这种方式运行。

如果你想设置一个值稍后用作返回值,使用变量:

yourfunc() {
  local retval=0

  for i in ...; do
    (( child_count >= 1 )) && retval=1
  done

  return "$retval"
}

【讨论】:

  • Haskell 的return 没有:)
  • @chepner,Haskell 完全保证语句之间的操作顺序?这并不像我期望的那样纯粹是功能性的。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-25
  • 2016-08-26
  • 1970-01-01
  • 2016-06-09
相关资源
最近更新 更多