Skip to main content

printf bash command



When writing a bash scripts most of us by default use echo command as means to print to standard output stream. echo is easy to use and mostly it fits our needs without any problem. However, with simplicity very often comes limitation. This is also the case with echo command. Formatting an echo command output can be a nightmare and very often impossible task to do.
The solution to this can be a good old friend of all C/C++ the “printf” tool. printf can be just as easily implemented into a bash script is it is used with C/C++ programs. This article describes some basics of printf along with practical examples:

Syntax

printf accepts a FORMAT string and arguments in a following general form:
# printf

In format prinft can have format specifiers, escape sequences or ordinary characters. When it comes to arguments it is usually text we would like to print to standard output stream. Let’s start with something simple from a bash shell command line:
          # printf “hello printf”
          hello printf#

At this point we have supplied and argument “hello”. Not the different behaviour in comparison to echo command. No new line had been printed out as it it in case of when using default setting of echo command. To print a new line we need to supply printf with format string with escape sequence \n ( new line ):
          # printf “%s\n” “hello printf”
          hello printf

The format string is applied to each argument:
          # printf “%s\n” "hello printf" "in" "bash script"
          hello printf
          in
          bash script

1. Format specifiers

As you could have seen in the previous simple examples we have used %s as a format specifier. The most commonly used printf specifiers are %s, %b, %d, %x and %f . The specifiers are replaced by a corresponding arguments. See the following example:
          # printf "%s\t%s\n" "1" "2 3" "4" "5"
1        2 3
4        5

In the example above we have supplied two specifiers %s to print TAB ( \t ) and NEWLINE ( \n ) to be used a s part of printf format string to print along with each argument. First \t is applied to argument “1” and \n is applied to argument “2 3”. If there are more arguments than specifiers the format string is reused until all arguments had been depleted. Specifier %s means to print all argument in literal form.

2. Examples

As we have now covered the very basics let’s see some more printf examples: Instead of %s specifiers we can use %b specifier which is essentially the same by it allows us to interpret escape sequences with an argument:
          # printf "%s\n" "1" "2" "\n3"
          1
          2
          \n3
          # printf "%b\n" "1" "2" "\n3"
          1
          2
         
          #

When it comes to printing a integers we can use %d specifier:
          # printf "%d\n" 255 0xff 0377 3.5
          255
          255
          255
          Bash: printf: 3.5: invalid number
          3

As you can see %d specifiers refuses to print anything than integers. To printf floating point numbers a %f specifier is our friend:
          # printf "%f\n" 255 0xff 0377 3.5
          255.000000
          255.000000
          377.000000
          3.500000

The default behaviour of %f printf specifier is to print floating point numbers with 6 decimal places. To limit a decimal places to 1 we can specify a precision in a following manner:
          # printf "%.1f\n" 255 0xff 0377 3.5
          255.0
          255.0
          377.0
          3.5

Formatting to three places with preceding with 0:
          for i in $( seq 1 10 ); do printf "%03d\t" "$i"; done
          001    002    003    004    005    006    007    008    009    010

Simple table. Format names to 7 places nad max 7 characters and format floating point number to 9 places with 2 decimals. More complicated sample script using printf formatting to create a table with multiple items. Save as a script make executable and run:
          #/bin/bash
divider===============================
divider=$divider$divider
header="\n %-10s %8s %10s %11s\n"
format=" %-10s %08d %10s %11.2f\n"
width=43
printf "$header" "ITEM NAME" "ITEM ID" "COLOR" "PRICE"
printf "%$width.${width}s\n" "$divider"
printf "$format" \
Triangle 13  red 20 \
Oval 204449 "dark blue" 65.656 \
Square 3145 orange .7

Output:
$ ./table

 ITEM NAME   ITEM ID      COLOR       PRICE
===========================================
 Triangle   00000013        red       20.00
 Oval       00204449  dark blue       65.66
 Square     00003145     orange        0.70

Comments

Popular posts from this blog

CentOS / Redhat : Configure CentOS as a Software Router with two interfaces

Linux can be easily configured to share an internet connection using iptables. All you need to have is, two network interface cards as follows: a) Your internal (LAN) network connected via eth0 with static ip address 192.168.0.1 b) Your external WAN) network is connected via eth1 with static ip address 10.10.10.1  ( public IP provided by ISP ) Please note that interface eth1 may have public IP address or IP assigned by ISP. eth1 may be connected to a dedicated DSL / ADSL / WAN / Cable router: Step # 1: Enable Packet Forwarding Login as the root user. Open /etc/sysctl.conf file # vi /etc/sysctl.conf Add the following line to enable packet forwarding for IPv4: net.ipv4.conf.default.forwarding=1 Save and close the file. Restart networking: # service network restart Step # 2: Enable IP masquerading In Linux networking, Network Address Translation (NAT) or Network Masquerading (IP Masquerading) is a technique of transceivin

Virtual Box and Alt/Tab Keys

I use virtual box for all my testing activities. It comes too often that I have a virtual box VM window open & I want to switch to my host machine to see some stuff like tutorials etc.. If you press the alt+tab combination it just works inside the VM & doesn't switches to host machine. In these scenarios you can press the host key once ( not hold it ) & then whatever you press goes to host machine. So in general where host key is the default Right Ctrl, just press Right Ctrl once & now press the alt+tab & it will switch you out to host machine. This is really helpful when you have the VM windows open or you're working on seamless mode. Hope it help others too.

AMD Radeon™ HD 7670M on Ubuntu 12.04

Update:   Recently I install kubuntu 13.10 and there is no problem with graphics. It just works  fine out of the box. I've seen many blog posts on how to make AMD HD7670M work on Ubuntu 12.04, specially when its in switchable graphics board like Dell Inspiron 15R 5520. I tried many things to make it work so that I could use the cinnamon desktop on ubuntu & other things too.. But to my surprise even the drivers from AMD site didn't work. Then I tried a combination of those blog posts I read & somehow I became successful in running the full graphics including compiz settings inside My Ubuntu Machine. Following are the steps I followed & it worked... 1. Create a backup of your xorg configuration file: sudo cp /etc/X11/xorg.conf /etc/X11/xorg.conf.BAK 2. Remove/purge current fglrx and fglrx-amdcccle : sudo apt-get remove --purge fglrx* 3. Install the driver: sudo apt-get install fglrx fglrx-amdcccle 4. Install additional