简体   繁体   English

为什么回声会产生换行符?

[英]Why is echo producing a newline?

What's the difference between 之间有什么区别

echo -n "
> "

and

echo -n ""

The first one produces a newline whereas the second doesn't. 第一个产生换行符,而第二个则不。

I'm running GNU bash, version 4.2.45(1)-release (x86_64-pc-linux-gnu) 我正在运行GNU bash,版本4.2.45(1)-发行版(x86_64-pc-linux-gnu)

Edit : I get that the input gets a newline here. 编辑:我得到输入在这里换行。 I should have been clearer with the question. 我应该对这个问题更清楚。 Consider the following script input.sh 考虑以下脚本input.sh

#!/bin/bash
echo -n $1

The following doesn't produce a newline. 以下不会产生换行符。

./input.sh "
> "

The string 字符串

"
 > "

has a newline in it as far as bash is concerned. 就bash而言,其中包含换行符。 The -n flag just means that echo will not print an extra newline at the end of your output. -n标志仅表示echo不会在输出末尾打印额外的换行符。 It will still reproduce your input, including newlines. 它仍然会重现您的输入,包括换行符。

Expanding on @chepner's comment. 扩展@chepner的评论。 Consider this: 考虑一下:

$ set -- "
"

$ echo -n "$1" | od -c
0000000  \n
0000001

$ echo -n $1 | od -c
0000000

When you leave the variable unquoted, any leading or trailing sequences of whitespace are removed by shell. 如果不加引号,shell将删除所有开头或结尾的空格序列。 So bash discards your newline when you don't quote $1. 因此,当您不报价$ 1时,bash会丢弃换行符。 This happens before "echo" is invoked, so "echo -n" is given no arguments . 这是在调用“ echo” 之前发生的,因此“ echo -n” 没有给出参数

From the Word Splitting section in the manual: 在手册的“分词”部分中:

If IFS is unset, or its value is exactly <space><tab><newline> , the default, then sequences of <space> , <tab> , and <newline> at the beginning and end of the results of the previous expansions are ignored, and any sequence of IFS characters not at the beginning or end serves to delimit words. 如果未设置IFS ,或者其值恰好是默认值<space><tab><newline> ,则在先前扩展结果的开头和结尾处分别是<space><tab><newline>序列会被忽略,并且任何不在开头或结尾的IFS字符序列都用于分隔单词。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM