[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: printf treats arguments of "%c" not as expected

From: Yunfeng Wang
Subject: Re: printf treats arguments of "%c" not as expected
Date: Thu, 23 Jun 2011 15:51:36 +0800

Hi Jonathan,

I didn't check the POSIX spec, my fault ;-)
So bash chooses to conform to POSIX regarding this behaviour, not bad I believe.
But the help message of printf is somewhat misleading as it says:

$ help printf
printf: printf [-v var] format [arguments]
    Formats and prints ARGUMENTS under control of the FORMAT.
    In addition to the standard format specifications described in printf(1)
    and printf(3), printf interprets:

while printf(3) describes %c as below:

$ man 3 printf
       c      If no l modifier is present, the int argument is converted to an
              unsigned  char, and the resulting character is written.

That's why I thought "printf %c 65" should have printed an 'A' instead of
the initial character '6'. I also checked Perl and found what I wanted:

$ perl -e 'printf "%c\n", 65'

Perhaps bash should clarify this issue in its documents such that users like me
would not be misguided again.


2011/6/23 Jonathan Nieder <address@hidden>:
> Hi,
> Yunfeng Wang wrote:
>>     $ printf %c 65 66 67
>>     666
>>     The expected output is ABC, i.e. characters with ASCII code of 65 66 67
> I believe the current behavior is correct.  POSIX (XCU.4.printf) sayeth[*]:
>        11. The argument to the 'c' conversion specifier can be a string
>            containing zero or more bytes.  If it contains one or more
>            bytes, the first byte shall be written and any additional bytes
>            shall be ignored.  If the argument is an empty string, it is
>            unspecified whether nothing is written or a null byte is written.
> I would suggest using something like
>        perl -e 'print(chr(65), chr(66), chr(67), "\n");'
> or
>        for i in 65 66 67
>        do
>                eval printf \'\\$(printf %03o "$i")\'
>        done
>        printf '\n'
> for your application.
> Back to the bug: I don't see any explanation of "printf %c" when I run
> "man bash".  Perhaps your manual is different from mine, but if you,
> perhaps it would be possible to suggest a few words to explain this
> for future readers.
> Thanks and regards,
> Jonathan
> [*] http://unix.org/2008edition/

reply via email to

[Prev in Thread] Current Thread [Next in Thread]