官术网_书友最值得收藏!

How it works...

While this is a pretty important topic revolving around data types (especially when dealing with math or calculations), we broke the solution to this recipe up into two parts:

  1. In step 1, echo is pretty straightforward. We have mentioned in the past that there are special characters and escapes. \t stands for tab \r\n a new line in Windows (although in Linux, \n\n would have sufficed) and again, we could print out a fancy UTF character:

$ bash echo-mayhem.sh
Currently we have seen the command "echo" used before in the previous script

Can we also have \t tabs? \r\n\r\n? NO, not yet!

Can we also have tabs?

? YES, we can now! enable interpretation of backslash escapes
We can also have:

Check the man pages for more info ;)

  1. However, the results of step 2 are a bit different, as we can see in the following code. Let's explore this a bit more as it looks like it's a bit more than sloppy alignment:
$ bash printf-mayhem.sh 
This is the same as echo -e with a new line (\n)
This is two decimal places: 10.00

shall we align:

3.333 6.666600
3.333333 6.666600
3.333333 6.666600
--------------------
Char Hex
N 0x4E
o 0x6F
0x20
p 0x70
l 0x6C
a 0x61
c 0x63
e 0x65
0x20
l 0x6C
i 0x69
k 0x6B
e 0x65
0x20
h 0x68
o 0x6F
m 0x6D
e 0x65
! 0x21
0x0
  1. As we can see, in the preceding step after execution, there are a few interesting things. The first thing we notice is that printf is echo on steroids; it provides the same functionality and far more such as alignment, strings being printed with %s, and decimal places (for example, %.2f). As we dig deeper, we can see that we can limit the number of decimal places using a % after the %tag. Notice the single character usually immediately after the % signthis is how you format the following parameters. Using a value like %10f, we are dedicating 10 spaces to the value, or rather, the width of 10 characters. If we use %-10, then it means we are aligning the value to the left. And besides the near horizontal rule, which uses expansion, we also "stepped" our way through the string "No place like home!". Using a while loop, we print out each ASCII character using (%-c) with its corresponding hexadecimal value (%-2X).
Notice that even spaces have a hexadecimal (hex) value, and that is 0x20. If you ran the script and got "printf-mayhem.sh: line 26: printf: !: invalid number", this is because you missed the single in  "'${STR:$TMP_CNT:1}". This signifies how to interpret the returned value as either a string/character or numeric value.
主站蜘蛛池模板: 湾仔区| 蒲城县| 凤凰县| 邹城市| 肃南| 新昌县| 镶黄旗| 阿克苏市| 登封市| 贵阳市| 清河县| 苍山县| 罗定市| 玛曲县| 颍上县| 兴仁县| 成安县| 介休市| 威海市| 郯城县| 开江县| 海南省| 罗源县| 绥棱县| 道真| 太白县| 香格里拉县| 淮安市| 涟水县| 石河子市| 兴隆县| 体育| 河东区| 称多县| 筠连县| 临猗县| 石嘴山市| 双流县| 洞头县| 栾城县| 郁南县|