加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

最后的新行“$(…)”在shell脚本中被删除.为什么?

发布时间:2020-12-15 21:47:11 所属栏目:安全 来源:网络整理
导读:有人能解释为什么这两个命令的输出不同吗? $echo "NewLine1nNewLine2n"NewLine1NewLine2 -- Note 2nd newline here$echo "$(echo "NewLine1nNewLine2n")"NewLine1NewLine2$ -- No second newline 有没有什么好办法可以在“$(….)”中将新行保留在输出的
有人能解释为什么这两个命令的输出不同吗?

$echo "NewLine1nNewLine2n"
NewLine1
NewLine2
                         <-- Note 2nd newline here
$echo "$(echo "NewLine1nNewLine2n")"
NewLine1
NewLine2
$                       <-- No second newline

有没有什么好办法可以在“$(….)”中将新行保留在输出的末尾?我想过只是添加一个虚拟字母并删除它,但我很想知道为什么这些新线条会消失.

解决方法

因为 that’s what POSIX specifies并且在Bourne shell中一直如此:

2.6.3 Command Substitution

Command substitution allows the output of a command to be substituted
in place of the command name itself. Command substitution shall occur
when the command is enclosed as follows:

$(command)

or (backquoted version):

`command`

The shell shall expand the command substitution by executing command
in a subshell environment (see Shell Execution Environment) and
replacing the command substitution (the text of command plus the
enclosing “$()” or backquotes) with the standard output of the
command,removing sequences of one or more <newline> characters at the
end of the substitution. Embedded <newline> characters before the end
of the output shall not be removed; however,they may be treated as
field delimiters and eliminated during field splitting,depending on
the value of IFS and quoting that is in effect. If the output contains
any null bytes,the behavior is unspecified.

保留最终换行符的一种方法是

VAR="$(command; echo x)"   # Append x to keep newline(s).
VAR=${VAR%x}               # Chop x.

可见:

$x="$(whoami; echo x)" ; printf '<%s>n' "$x" "${x%x}"
<user
x>
<user
>

但为什么删除尾随换行符?因为通常你会这样想.我也在使用perl进行编程,我无法计算读取行或变量的次数,然后需要切换换行符:

while (defined ($string = <>)) {
    chop $string;
    frobnitz($string);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读