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

  • Bash Cookbook
  • Ron Brash Ganesh Naik
  • 458字
  • 2021-07-23 19:17:37

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.
主站蜘蛛池模板: 定襄县| 迁西县| 东阿县| 清远市| 寻乌县| 曲靖市| 阿合奇县| 鲁山县| 雅江县| 苏尼特左旗| 承德市| 无棣县| 临沭县| 洛宁县| 桑植县| 凤庆县| 宁河县| 卢湾区| 滕州市| 遵义县| 阿坝县| 阜新| 密云县| 阿克苏市| 三河市| 阜城县| 连南| 时尚| 华容县| 大竹县| 紫金县| 太和县| 怀柔区| 竹山县| 哈尔滨市| 教育| 宝丰县| 澎湖县| 灌阳县| 西乡县| 龙岩市|