[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: printf "%q" and $'...'
From: |
Greg Wooledge |
Subject: |
Re: printf "%q" and $'...' |
Date: |
Wed, 25 Nov 2009 08:31:10 -0500 |
User-agent: |
Mutt/1.4.2.3i |
> On 25 Nov 2009, at 08:19, Antonio Macchi wrote:
> > Hi, I'm using older bash 3.2.39, so please forgiveme if in your newer bash
> > this issue does not arise.
On Wed, Nov 25, 2009 at 08:25:00AM +0100, Maarten Billemont wrote:
> As for NUL out outputting anything in your result, the cause is C-strings.
> Arguments are C-strings and those are delimited by NUL bytes. Therefore, the
> NUL byte that you're putting in it is actually marking the end of the string.
> So the argument ends BEFORE your NUL byte. So it's empty.
>
> As or \x0a, that's a newline. And command substitution trims trailing
> newlines. So a string "[newline]" gets trimmed to "".
If the goal is to get content including trailing newlines into a bash
variable using printf, then Antonio can use printf -v:
imadev:~$ printf -v myvar '%q\n' $'\x0a'
imadev:~$ echo "$myvar"
$'\n'
(Note blank line in the output -- one newline from the echo command,
and one from the actual content of $myvar.) Using printf -v instead of
x=$(printf) means you don't suffer from the trailing-newline-removal
that command substitution does.
I'm a bit puzzled by the original e-mail, though. I don't see what the
actual goal is. If the goal is simply "put a newline character into a
variable", then this is even simpler:
myvar=$'\n'