{"id":160766,"date":"2021-01-22T17:00:02","date_gmt":"2021-01-22T14:00:02","guid":{"rendered":"https:\/\/en.buradabiliyorum.com\/how-to-use-printf-in-bash-cloudsavvy-it\/"},"modified":"2021-01-22T17:00:02","modified_gmt":"2021-01-22T14:00:02","slug":"how-to-use-printf-in-bash-cloudsavvy-it","status":"publish","type":"post","link":"https:\/\/buradabiliyorum.com\/en\/how-to-use-printf-in-bash-cloudsavvy-it\/","title":{"rendered":"#How to Use printf in Bash \u2013 CloudSavvy IT"},"content":{"rendered":"<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_84 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<label for=\"ez-toc-cssicon-toggle-item-6a2432b1f2590\" class=\"ez-toc-cssicon-toggle-label\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #dd3333;color:#dd3333\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #dd3333;color:#dd3333\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/label><input type=\"checkbox\"  id=\"ez-toc-cssicon-toggle-item-6a2432b1f2590\" checked aria-label=\"Toggle\" \/><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/buradabiliyorum.com\/en\/how-to-use-printf-in-bash-cloudsavvy-it\/#Using_printf_in_Bash\" >Using printf in Bash<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/buradabiliyorum.com\/en\/how-to-use-printf-in-bash-cloudsavvy-it\/#Syntax_printf\" >Syntax:\u00a0printf<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/buradabiliyorum.com\/en\/how-to-use-printf-in-bash-cloudsavvy-it\/#Examples_printf\" >Examples:\u00a0printf<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/buradabiliyorum.com\/en\/how-to-use-printf-in-bash-cloudsavvy-it\/#Conclusion\" >Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<p><strong>&#8220;#How to Use printf in Bash \u2013 CloudSavvy IT&#8221;<\/strong><\/p>\n<div id=\"article-content-area\">\n<figure id=\"attachment_9116\" style=\"width: 700px\" class=\"wp-caption alignnone\"><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-9116 size-full\" src=\"https:\/\/www.cloudsavvyit.com\/thumbcache\/0\/0\/28eefb37e13055c91b4a7d6ddbb64433\/p\/uploads\/2021\/01\/cd68a4cb.png\" alt=\"\" width=\"700\" height=\"300\" data-crediturl=\"https:\/\/www.shutterstock.com\/image-photo\/format-word-pink-keyboard-buttons-1038597418\" data-credittext=\"Shutterstock\/gilangtristiano\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><figcaption class=\"wp-caption-text\"><span class=\"imagecredit\"><a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/www.shutterstock.com\/image-photo\/format-word-pink-keyboard-buttons-1038597418\">Shutterstock\/gilangtristiano<\/a><\/span><\/figcaption><\/figure>\n<p>Text formatting is an interesting topic, especially when it comes to Bash. Whilst there are many tools for text formatting, printf is unique and universal. Learn all about printf in Bash to format your text just the right way!<\/p>\n<h2 role=\"heading\" aria-level=\"2\"><span class=\"ez-toc-section\" id=\"Using_printf_in_Bash\"><\/span>Using <em>printf<\/em> in Bash<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>C++ and other developers will already be familiar with printf as a great way to format the output of text when programming. To have the same tool available in Bash is of great benefit. printf allows you to control and produce complex output formats, just the way you want it. The printf manual page defines printf as a \u2018format and print data\u2019 tool, which is exactly what it is and does.<\/p>\n<p>For example, would you like to print a decimal based number with an exact length of 3 bytes (or characters\/numbers) for the integer part (the part before the decimal dot or comma, depending on where in the world you live and what your locale is) and 2 bytes (or characters\/numbers) for the decimal part of the number? <em>No problem<\/em>, printf can do it and much more. It could also output the text to a specific column on the screen, etc.<\/p>\n<p>Though the syntax of printf, for a new developer, may look confusing or complex, it is actually quite straightforward. There are only a limited set of commonly employed formatting characters which can be used within a printf output definition. Let\u2019s have a look at these first.<\/p>\n<h2 role=\"heading\" aria-level=\"2\"><span class=\"ez-toc-section\" id=\"Syntax_printf\"><\/span>Syntax:\u00a0<i>printf<\/i><span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>These are the most commonly used <i>printf syntax<\/i> number formatting idioms:<\/p>\n<pre>%d or %i  a signed decimal integer&#13;\n%u        an unsigned decimal integer&#13;\n%f        a decimal floating point number&#13;\n%e        a scientific notation number&#13;\n%g        will let printf use %e or %f, whichever is shorter&#13;\n%c        a single character&#13;\n%s        a string of characters&#13;\n%%        a literal '%'&#13;\n<\/pre>\n<p>Next, it is good to know how to specify specific options in connection with these formatting idioms. The format for specifying options for these is as follows:<\/p>\n<pre>%[flag(s)][width][.precision][length]number_formatting_idiom&#13;\n<\/pre>\n<h2 role=\"heading\" aria-level=\"2\"><span class=\"ez-toc-section\" id=\"Examples_printf\"><\/span>Examples:\u00a0<i>printf<\/i><span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>So for example, to have a float with a width of 3, and a precision of 2, you would specify:<\/p>\n<pre>%3.2f&#13;\n<\/pre>\n<p>Let\u2019s look at an example:<\/p>\n<pre>printf \"%3.2fn\" \"100.304\" &#13;\n<\/pre>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-9109\" src=\"https:\/\/www.cloudsavvyit.com\/thumbcache\/0\/0\/73a17d5af67f5d19930e1f8ed978a713\/p\/uploads\/2021\/01\/441536d1.png\" alt=\"Printing a well formatted float with printf\" width=\"243\" height=\"53\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/p>\n<p>Straightforward and easy. Note that we could have used a variable instead of <code>\"100.304\"<\/code>:<\/p>\n<pre>VAR1=100.304&#13;\nprintf \"%3.2fn\" ${VAR1}&#13;\n<\/pre>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-9110\" src=\"https:\/\/www.cloudsavvyit.com\/thumbcache\/0\/0\/0882b4d532a4dcd3f04d5842d08315a8\/p\/uploads\/2021\/01\/3cbfcbf5.png\" alt=\"Printing a formatted float with printf using a Bash variable\" width=\"240\" height=\"69\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/p>\n<p>Note also how we added a newline by using a <code>n<\/code> newline sequence. For a full list of available interpreted sequences, see <code>man printf<\/code>. The most common ones are <code>n<\/code> for newline, <code>t<\/code> for tab and <code>\\<\/code> for a backslash.<\/p>\n<p>In the options format above we also saw how we can specify flags. There are a limited amount of common flags:<\/p>\n<pre>-   Left-justify text (right-justify is the default)&#13;\n+   Forces the use of a sign, even if positive&#13;\n' ' A space is inserted if no sign will be used&#13;\n0   Left-pad the number with zeroes instead of spaces when padding is specified&#13;\n<\/pre>\n<p>Thus, for example, we can have:<\/p>\n<pre>VAR1=-100.304&#13;\nVAR2=100.304&#13;\nprintf \"% 3.2ftt%+3.2fn\" ${VAR1} ${VAR2}&#13;\n<\/pre>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-9111\" src=\"https:\/\/www.cloudsavvyit.com\/thumbcache\/0\/0\/b79e1e9313893d4ddfab4d51b9546c9b\/p\/uploads\/2021\/01\/0d5e261f.png\" alt=\"Printing negative numbers with printf and formatting\" width=\"391\" height=\"83\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/p>\n<p>Here we used two variables, and separated the output by two tabs using two <code>t<\/code> tab sequences. We also inserted a space (as a flag) in between <code>%<\/code> and the width definition. This led to the negative number in <code>VAR1<\/code> to be printed using a negative sign. If the number would have been positive, no sign would have been printed, and instead a space would be printed in the same position.<\/p>\n<p>Finally we used the <code>+<\/code> flag and indeed our number is output with a leading <code>+<\/code> sign irrespective of the fact that the number is already positive and thus (normally) no sign would be printed.<\/p>\n<p>So how can we ensure that we have leading zeros or spaces, while still having a specific length? First, we have to ensure our definition width is longer then variable contents, and secondly we can use the <code>0<\/code> flag to show leading zeros:<\/p>\n<pre>VAR1=-100.304&#13;\nVAR2=100.304&#13;\nprintf \"% 13.2fn%013.2fn%13.2f\" ${VAR1} ${VAR2} ${VAR1}&#13;\n<\/pre>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-9112\" src=\"https:\/\/www.cloudsavvyit.com\/thumbcache\/0\/0\/cc40c7e12daea400273ed63b3427c350\/p\/uploads\/2021\/01\/3f0f9f51.png\" alt=\"Output formatting for printf and leading zeroes definition\" width=\"487\" height=\"103\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/p>\n<p>In this example, we print 3 lines, separated two times by the <code>n<\/code> newline sequence. We im<a href=\"https:\/\/buradabiliyorum.com\/en\/category\/social-mediaa\/\" data-internallinksmanager029f6b8e52c=\"1\" title=\"Social Media\" target=\"_blank\" rel=\"noopener\">media<\/a>tely note that if there is no newline at the end of the output, that our Bash prompt returns specifically at the end of our 3rd line of output.<\/p>\n<p>This may not be a nice or handy format in interactive mode in the terminal, but from within a <a href=\"https:\/\/buradabiliyorum.com\/en\/category\/download-scripts-themes-apps\/\" data-internallinksmanager029f6b8e52c=\"9\" title=\"Download Scripts &amp; Themes &amp; Apps\" target=\"_blank\" rel=\"noopener\">script<\/a> (think for example about a sequence like <code>1...2...3...<\/code> which builds step by step on the screen as progress within the code is made) this can be very handy.<\/p>\n<p>In the second line of output, we use the <code>0<\/code> flag to indicate we would like to use leading zeroes for <code>VAR2<\/code>. The output indeed yields leading zeroes, up to the defined length.<\/p>\n<p>In the first line of output, we inserted a space whereas in the third line of output (both printing the <code>VAR1<\/code> variable) we did not. The output is the same, which is the only oddity I ever found while working with <code>printf<\/code>; one would expect there to be one additional character given the <i>printf space flag definition<\/i>. This remains the same even if we would use leading zeroes. It also remains the same if no length is specified.<\/p>\n<p>The usability of the space flag may thus in some cases (negative numbers) be limited. This is not the case for positive numbers:<\/p>\n<pre>VAR1=100.304&#13;\nprintf \"% fn%0fn\" ${VAR1} ${VAR1}&#13;\n<\/pre>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-9113\" src=\"https:\/\/www.cloudsavvyit.com\/thumbcache\/0\/0\/95b95c367099bc617592a0017bbc8b8c\/p\/uploads\/2021\/01\/2510dd7c.png\" alt=\"A leading space in positive numbers based on the special space flag\" width=\"309\" height=\"87\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/p>\n<p>In this case (positive numbers), the <i>space flag<\/i> works as expected, and an extra space is inserted in the case of the first <code>VAR1<\/code> output.<\/p>\n<h2 role=\"heading\" aria-level=\"2\"><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Using printf from within Bash scripts or at the command line can yield clear well-defined output. If you scale variables correctly (and perhaps range check them for certainty), using <i>printf<\/i> will give you a flexible method to format the output (and overall screen layout for larger applications) as you choose.<\/p>\n<p>In this article we look at commonly used number formatting idioms, how to define the width of both the integer and decimal part of numbers, and reviewed the most commonly used flags in printf. Enjoy printing well-formatted data with printf!\n<\/p><\/div>\n<blockquote><p><strong><span style=\"color: #ff6600;\">If you liked the article, do not forget to share it with your friends. Follow us on\u00a0<span style=\"color: #ff0000;\"><a style=\"color: #ff0000;\" href=\"https:\/\/news.google.com\/publications\/CAAqBwgKMLG0nwswvr63Aw\" target=\"_blank\" rel=\"nofollow noopener noreferrer\">Google News<\/a><\/span>\u00a0too, click on the star and choose us from your favorites.<\/span><\/strong><\/p><\/blockquote>\n<blockquote>\n<p style=\"text-align: center;\">For forums sites go to <span style=\"color: #ff9900;\"><a style=\"color: #ff9900;\" href=\"https:\/\/forum.buradabiliyorum.com\/\" target=\"_blank\" rel=\"noopener\">Forum.BuradaBiliyorum.Com<\/a><\/span><\/strong><\/p>\n<\/blockquote>\n<blockquote>\n<p style=\"text-align: center;\"><strong>If you want to read more like this article, you can visit our <span style=\"color: #ff9900;\"><a style=\"color: #ff9900;\" href=\"https:\/\/en.buradabiliyorum.com\/technology\/\" target=\"_blank\" rel=\"noopener\">Technology category.<\/a><\/span><\/strong><\/p>\n<\/blockquote>\n<p><span style=\"color: black;\"><a style=\"color: #ff9900;\" href=\"https:\/\/www.cloudsavvyit.com\/9108\/how-to-use-printf-in-bash\/\" target=\"_blank\" rel=\"noopener\">Source<\/a><\/span><\/p>\n","protected":false},"excerpt":{"rendered":"<p>&#8220;#How to Use printf in Bash \u2013 CloudSavvy IT&#8221; Shutterstock\/gilangtristiano Text formatting is an interesting topic, especially when it comes to Bash. Whilst there are many tools for text formatting, printf is unique and universal. Learn all about printf in Bash to format your text just the right way! Using printf in Bash C++ and&#8230;<\/p>\n","protected":false},"author":1,"featured_media":160767,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"fifu_image_url":"https:\/\/www.cloudsavvyit.com\/p\/uploads\/2021\/01\/cd68a4cb.png","fifu_image_alt":"","footnotes":""},"categories":[18],"tags":[],"class_list":["post-160766","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-technology"],"_links":{"self":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/posts\/160766","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/comments?post=160766"}],"version-history":[{"count":0,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/posts\/160766\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/media\/160767"}],"wp:attachment":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/media?parent=160766"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/categories?post=160766"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/tags?post=160766"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}