views:

105

answers:

4

I have a bash shell script which has the line:

g=$(/bin/printf ${i})

when ${i} contains something like -6, printf thinks its being passed an option. It does not recognize the option so produces an error.

if wrap ${i} in quotes, printf still thinks its being passed an option.

g=$(/bin/printf "${i}")

if I escape the quotes, variable $g then holds "-6" which is not what I want either.

g=$(/bin/printf \"${i}\")

Is there away to escape the dash (-).

printf is a BusyBox app

+9  A: 

Most GNU programs support using -- as a delimiter to tell the program that all further arguments are not options. For instance

$ printf -- -6
-6
Jack Lloyd
thanks. That would work, but my printf is a BusyBox version, which does not support that option. any other ideas.
Andrew
@Andrew In that case a format string as ndim suggested is probably the way to go. I've added the busybox tag to your question so this is obvious for future readers.
Jack Lloyd
+1  A: 

You should use

printf -- -6
tangens
+5  A: 

What if you called printf with an actual format string?

$ printf "%d\n" -6
-6
$ /sbin/busybox printf "%d\n" -6
-6
$

This works with both GNU coreutils' and busybox' printf, apparently.

ndim
this works - though I think there is a reason the script does not do this already. As it could just simple use echo. However it works for now, but if anyone as a better solution, I would be interested.
Andrew
Well, if it is just a question of %d... then you could just do `g=$i` and be done without invoking another process at all.
ndim
${i} could be anything, number, string etc. Any value starting with '-' will cause printf to fail.
Andrew
Exactly. So we have now solved the issue of how to get printf(1) to handle a negative number in `$i`. However, the issue of how your script arrives at that value for `$i` and how it proceeds with the new `$g` is an entirely different beast.
ndim
A: 

If you feed a non-numeric argument in this way, you get an error message:

$ busybox printf "%d" "a"
a: conversion error
-1

But you can use %s and it will work for both numeric and non-numeric arguments (as long as you don't need to do any formatting):

$ busybox printf "%s" "a"
a
$ busybox printf "%s" -6
-6

If you're not using the formatting features of printf and you need to output the value without a newline, busybox's echo command supports -n:

$ busybox echo -n "a"
a
$ busybox echo -n -6
-6
Dennis Williamson