0

This is in bash(5.0.3(1)-release) / ubuntu 19

When I ran :

printf "%s" $'\n'

It printed out a new line.

Now when I run:

result="$(printf "%s" $'\n')"
printf "<%s>" "$result"

I expect $result contains a newline, but it's empty.

Can someone explain ?

Philippe
  • 20,025
  • 2
  • 23
  • 32

1 Answers1

2

From posix shell manual, from chapter about process substitution, emphasis mine:

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

It's impossible to store trailing newlines with process substitution. You can use for example printf -v bash extension:

printf -v result "%s" $'\n'

For most portability, I go with encoding the string in hex using od or xxd and store the string in hex. Or just store the resulting string in a file.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111