arcyqwerty arcyqwerty - 2 months ago 9
Bash Question

Hexdump conversion string surrounded by escaped characters in format string

I am trying to get the following result from

hexdump
:

78 79 7a


which is
"\t78\t\t79\t\t7a\t"


Trying

echo -n xyz | hexdump -e '1/1 "\t%x\t"'


Results in an error:

hexdump: % : bad conversion character


But

echo -n xyz | hexdump -e '1/1 "|%x|"'


Correctly yields

|78||79||7a|


Adding spaces:

echo -n xyz | hexdump -e '1/1 "\t %x \t"'


does something:

t 78 t 79 t 7a


which is
"\tt 78\t\tt 79\t\tt 7a\t"
but I'm getting both the desired tabs and the literal letter
t
plus some unwanted space characters.

It works when using just a single trailing tab

echo -n xyz | hexdump -e '1/1 "%x\t"'


gives me

78 79 7a


which is
"78\t79\t7a\t"
but not for a single leading tab

echo -n xyz | hexdump -e '1/1 "\t%x"'


which gives me another error

hexdump: %A: bad conversion character


I'm not sure where that error is coming from since there is no
%A
anywhere.

According to the man page,
\t
should be a supported escape sequence and I'm treating it like any other character in printf.


The format is required and must be surrounded by double quote (" ")
marks. It is interpreted as a fprintf-style format string (see
fprintf(3)), with the following exceptions:

+o An asterisk (*) may not be used as a field width or precision.

+o A byte count or field precision is required for each ``s'' con-
version character (unlike the fprintf(3) default which prints
the entire string if the precision is unspecified).

+o The conversion characters ``h'', ``l'', ``n'', ``p'' and ``q''
are not supported.

+o The single character escape sequences described in the C stan-
dard are supported:

NUL \0
<alert character> \a
<backspace> \b
<form-feed> \f
<newline> \n
<carriage return> \r
<tab> \t
<vertical tab> \v


Answer

This behavior is actually a fixed, not so long ago, bug. For affected versions there's a workaround: just put the leading slash into a separate format string.

For example, the code you wanted would look like:

echo -n xyz | hexdump -e '"\t" 1/1 "%x"'
Comments