Traço, substituição de comando não inserindo nova linha?

1

Basicamente, este é o problema:

$ echo Hello"$(printf '\n')"World
HelloWorld

O que eu ignorei?

    
por Sergiy Kolodyazhnyy 05.06.2018 / 01:27

1 resposta

2

Esse comportamento é, na verdade, parte da especificação do POSIX para a substituição de comandos :

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 characters at the end of the substitution. Embedded 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.

Portanto, a regra de cotação normal "$(...)" apenas preserva as novas linhas não finais.

Algumas sugestões para preservar as novas linhas finais são fornecidas na shell: manter novas linhas ('\ n') na substituição de comando

Veja também Ao imprimir uma variável que contém novas linhas, por que a última nova linha foi removida? para discussão das razões por trás da especificação.

    
por steeldriver 05.06.2018 / 01:43