| 1 | #!/bin/bash |
| 2 | # printf demo |
| 3 | |
| 4 | declare -r PI=3.14159265358979 # Read-only variable, i.e., a constant. |
| 5 | declare -r DecimalConstant=31373 |
| 6 | |
| 7 | Message1="Greetings," |
| 8 | Message2="Earthling." |
| 9 | |
| 10 | echo |
| 11 | |
| 12 | printf "Pi to 2 decimal places = %1.2f" $PI |
| 13 | echo |
| 14 | printf "Pi to 9 decimal places = %1.9f" $PI # It even rounds off correctly. |
| 15 | |
| 16 | printf "\n" # Prints a line feed, |
| 17 | # Equivalent to 'echo' . . . |
| 18 | |
| 19 | printf "Constant = \t%d\n" $DecimalConstant # Inserts tab (\t). |
| 20 | |
| 21 | printf "%s %s \n" $Message1 $Message2 |
| 22 | |
| 23 | echo |
| 24 | |
| 25 | # ==========================================# |
| 26 | # Simulation of C function, sprintf(). |
| 27 | # Loading a variable with a formatted string. |
| 28 | |
| 29 | echo |
| 30 | |
| 31 | Pi12=$(printf "%1.12f" $PI) |
| 32 | echo "Pi to 12 decimal places = $Pi12" # Roundoff error! |
| 33 | |
| 34 | Msg=`printf "%s %s \n" $Message1 $Message2` |
| 35 | echo $Msg; echo $Msg |
| 36 | |
| 37 | # As it happens, the 'sprintf' function can now be accessed |
| 38 | #+ as a loadable module to Bash, |
| 39 | #+ but this is not portable. |
| 40 | |
| 41 | exit 0 |