bash 摆脱“警告:命令替换:输入中忽略空字节”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46163678/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 22:36:22  来源:igfitidea点击:

Get rid of "warning: command substitution: ignored null byte in input"

bash

提问by SBF

I'm getting -bash: warning: command substitution: ignored null byte in inputwhen I run model=$(cat /proc/device-tree/model)

我收到-bash: warning: command substitution: ignored null byte in input的时候我跑model=$(cat /proc/device-tree/model)

bash --version
GNU bash, version 4.4.12(1)-release (arm-unknown-linux-gnueabihf)

With bash version 4.3.30 it's all OK

使用 bash 版本 4.3.30 一切正常

I understand the problem is the terminating \0character in the file, but how can I suppress this stupid message? My whole script is messed up since I'm on bash 4.4

我知道问题是\0文件中的终止字符,但我如何才能抑制这个愚蠢的消息?自从我使用 bash 4.4 以来,我的整个脚本都搞砸了

采纳答案by Charles Duffy

There are two possible behaviors you might want here:

您可能需要两种可能的行为:

  • Read until first NUL. This is the more performant approach, as it requires no external processes to the shell. Checking whether the destination variable is non-empty after a failure ensures a successful exit status in the case where content is read but no NUL exists in input (which would otherwise result in a nonzero exit status).

    IFS= read -r -d '' model </proc/device-tree/model || [[ $model ]]
    
  • Read ignoring all NULs. This gets you equivalent behavior to the newer (4.4) release of bash.

    model=$(tr -d '
    model=""
    while IFS= read -r -d '' substring || [[ $substring ]]; do
      model+="$substring"
    done </proc/device-tree/model
    
    ' </proc/device-tree/model)

    You could also implement it using only builtins as follows:

    IFS= read -r -d '' model </proc/device-tree/model || [[ $model ]]
    
  • 读到第一个 NUL。这是一种性能更高的方法,因为它不需要外壳程序的外部进程。在读取内容但输入中不存在 NUL(否则会导致非零退出状态)的情况下,检查失败后目标变量是否为非空可确保成功退出状态。

    model=$(tr -d '
    model=""
    while IFS= read -r -d '' substring || [[ $substring ]]; do
      model+="$substring"
    done </proc/device-tree/model
    
    ' </proc/device-tree/model)
  • 阅读忽略所有 NUL。这使您具有与较新 (4.4) 版本的 bash 等效的行为。

    model=$(tr -d '##代码##' < /proc/device-tree/model)
    

    您也可以仅使用内置函数来实现它,如下所示:

    ##代码##

回答by Kevin

If you just want to delete the null byte:

如果您只想删除空字节:

##代码##