Linux – printf – Proper Usage

Background

I ran into problems with a little bash code that I was writing.

I was trying to use the printf code format command.

 

Code

Here is the original code.

Original Code


iNumberofProducts=10
strProductName="Apple"
dCostPerProduct=1.25

dProductSubTotal=`echo "$iNumberofProducts*$dCostPerProduct"|bc`

FORMAT_PRODUCT_DETAIL="%d %s at  %.2f each for a sub-total of %.2f \n"

printf $FORMAT_PRODUCT_DETAIL  $iNumberofProducts $strProductName $dCostPerProduct $dProductSubTotal

 

Output

Textual


printf.sh: line 11: printf: %s: invalid number
printf.sh: line 11: printf: at: invalid number
printf.sh: line 11: printf: %.2f: invalid number
printf.sh: line 11: printf: each: invalid number
printf.sh: line 11: printf: for: invalid number
printf.sh: line 11: printf: a: invalid number
printf.sh: line 11: printf: sub-total: invalid number
printf.sh: line 11: printf: of: invalid number
printf.sh: line 11: printf: %.2f: invalid number
printf.sh: line 11: printf: \n: invalid number
printf.sh: line 11: printf: Apple: invalid number
printf.sh: line 11: printf: 1.25: invalid number
printf.sh: line 11: printf: 12.50: invalid number


 

Revised Code

Code


iNumberofProducts=10
strProductName="Apple"
dCostPerProduct=1.25

dProductSubTotal=`echo "$iNumberofProducts*$dCostPerProduct"|bc`

FORMAT_PRODUCT_DETAIL="%d %s at %.2f each for a sub-total of %.2f \n"

printf "$FORMAT_PRODUCT_DETAIL" $iNumberofProducts $strProductName $dCostPerProduct $dProductSubTotal


Code

The solution is pretty simple and it is to quote the format string.

Simply replace printf $FORMAT_PRODUCT_DETAIL with printf $FORMAT_PRODUCT_DETAIL .

 

 

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s