How to get $ (/ bin / printf -6) to return -6 rather than thinking -6 is an option

I have a bash script shell that has a line:

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

when ${i} contains something like -6 , printf thinks the option is passed to it. It does not recognize the parameter, so an error occurs.

if wrap ${i} in quotation marks, printf still thinks that an option is passed to it.

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

if I run away from quotes, the variable $g , then " -6 " is executed, which is also not what I want.

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

Get out to avoid the dash (-).

printf is a BusyBox application

+4
source share
4 answers

What if you called printf with the 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.

+7
source

Most GNU programs support using -- as a separator to tell the program that all additional arguments are not parameters. For instance,

 $ printf -- -6 -6 
+12
source

You have to use

 printf -- -6 
+1
source

If you pass a non-numeric argument 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 (unless you need to format):

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

If you do not use the printf formatting functions, and you need to print the value without a new line, the busybox echo command supports -n :

 $ busybox echo -n "a" a $ busybox echo -n -6 -6 
0
source

All Articles