1

I am porting my shell script (quite big shell script) from bash to android shell (mksh shell).

In Android, printf does not seem to be working the same way as it works in other Linux systems.

Sample code :

$ cat sample.sh 
...
func1()
{
    A=100
    HEXA=`printf "%04x" ${A}`
    echo "A - ${A} HEXA - ${HEXA}"
}

func1

This function's output is as follows.

$ ./sample.sh
A - 100 HEXA - 300000078

It is printing a really weird number.

I saw from other posts and from the manpage of mksh that printf is not recommended to be used in mksh. My shell script, which is quite big, is using it very heavily. So, I want to handle this somehow. What are my options to handle this?

Alex P.
  • 30,437
  • 17
  • 118
  • 169
Sandeep
  • 18,356
  • 16
  • 68
  • 108
  • 1
    do `readlink -f $(whence printf)`. if your android is recent enough it would link to `toybox` – Alex P. Nov 18 '16 at 16:05
  • 1
    @AlexP. Yes it is referring to toybox and issue turned out to be in toybox. The issue is fixed now. I pasted details in my answer. Thank you. – Sandeep Nov 19 '16 at 02:12
  • Why so many down votes without any related commments? – Sandeep Nov 19 '16 at 21:24
  • 1
    my guess would be that using a popular tag like `bash` brought over some people, who then did not find anything `bash` related in the question and felt like they wasted their time – Alex P. Nov 24 '16 at 17:26
  • Not an issue in `mksh` as it’s not built with `printf` as builtin. But I’ll clarify the manpage. – mirabilos Jan 31 '17 at 18:30

2 Answers2

2

printf in Android is linking to toybox

root:/ # which printf
/system/bin/printf
root:/ # ls -l /system/bin/printf
lrwxr-xr-x root     shell             2016-11-14 21:02 printf -> toybox

So the issue turned out to be in toybox printf.

The issue is now fixed - https://github.com/landley/toybox/issues/54

Sandeep
  • 18,356
  • 16
  • 68
  • 108
2

Fixing printf in toybox is great.

But in case anyone would like to print out a number converted to hex (or pretty much any other reasonable base from 2 to 36 if they would be so inclined) on an unrooted device with the old toybox (or no toybox at all) - here is a way how to do it using typeset built-in of mksh:

baseconv(){ typeset -Ui${3:-16} -Z35 x=$1; echo ${x: -${2:-8}};}

func1()
{
    A=100
    HEXA=$(baseconv $A 4 16)
    echo "A - ${A} HEXA - ${HEXA}"
}

or just make a specific function for the printf "%04x" case:

printf04x(){ typeset -Ui16 -Z7 x=$1; echo ${x: -4};}

func1()
{
    A=100
    echo "A - ${A} HEXA - $(printf04x $A)"
}
Alex P.
  • 30,437
  • 17
  • 118
  • 169