- Bash Cookbook
- Ron Brash Ganesh Naik
- 300字
- 2021-07-23 19:17:35
Math and calculations in script
After a grueling introduction to the world of wildcards and regexes for searches, we're going to move on to being able to perform some basic mathematical operations at the console. If you haven't already tried, what happens when you run something like the following in the Bash shell? Does it look like this?
$ 1*5
1*5: command not found
Command not found? Certainly, we know the computer can do math, but clearly Bash is unable to interpret mathematical operations in this way. We have to ensure that Bash is able to interpret these operations correctly through the use of:
- The expr command (antiquated)
- The bc command
- POSIX Bash shell expansion
- Another language/program to do the dirty work
Let's try again, but using the POSIX Bash shell expansion:
$ echo $((1*5))
5
We got the expected answer of 5, but where does this go wrong? It goes wrong when using division and floats because Bash works primarily with integers:
$ echo $((1/5))
0
True, 1 divided by 5 is 0, but there is a remainder missing! And this is why we may rely on other methods to perform simple mathematics.
One of the many uses or reasons to use equations and math in a script is to determine sizes of file system partitions. Can you imagine what may happen if a disk becomes too full? Or that we may want to automatically archive a directory if it reaches a predetermined size? Of course, this is theoretical, but things can and do break if we let a file system silently become full!
The following recipe is about determining the size of a tarball (and contents), the remaining available space on the destination partition, and whether the operation could continue or be canceled.
- 數(shù)據(jù)庫系統(tǒng)教程(第2版)
- C語言程序設(shè)計(jì)實(shí)訓(xùn)教程
- PHP+MySQL網(wǎng)站開發(fā)技術(shù)項(xiàng)目式教程(第2版)
- VSTO開發(fā)入門教程
- Bootstrap Essentials
- Amazon S3 Cookbook
- Java軟件開發(fā)基礎(chǔ)
- 零基礎(chǔ)學(xué)Python網(wǎng)絡(luò)爬蟲案例實(shí)戰(zhàn)全流程詳解(入門與提高篇)
- 精通MySQL 8(視頻教學(xué)版)
- Mastering Apache Camel
- Using Yocto Project with BeagleBone Black
- Keil Cx51 V7.0單片機(jī)高級(jí)語言編程與μVision2應(yīng)用實(shí)踐
- 關(guān)系數(shù)據(jù)庫與SQL Server 2012(第3版)
- C#網(wǎng)絡(luò)編程高級(jí)篇之網(wǎng)頁游戲輔助程序設(shè)計(jì)
- Lync Server Cookbook