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

Getting ready

This recipe is going to take into account a few interesting things:

  • Bash can't do everything well
  • Other utilities exist (for example, bc)
  • We can create our own in another language like C
  • Creating a tarball
Sometimes, on small embedded systems, Python might not be available, but Bash (or a close relative) and C are. This is where being able to perform math without extra programs (that may not be available) can come in handy!

We will use the following command to make sure that we have all of the utilities installed for this experiment:

$ sudo apt-get install -y bc tar

Now, we need to create a tarball called archive.tar.gz:

$ dd if=/dev/zero of=empty.bin bs=1k count=10000
$ tar
-zcvf archive.tar.gz empty.bin
$ rm empty.bin

We realize that the purpose of creating/compiling a simple program that is not written in Bash may be beyond the scope of this book, but it can be a helpful skill. To do this, we will need to install GCC, which is short for the GNU Compiler Collection. This sounds terribly complex and we assure you that we did all the hard work:

$ sudo apt-get install -y gcc

The preceding command installs the compiler, and now we need the C source code (in order to compile a simple C program). Open up a console and retrieve the code using:

$ wget https://raw.githubusercontent.com/PacktPublishing/Bash-Cookbook/master/chapter%2002/mhelper.c
This code is also available on Github at https://github.com/PacktPublishing/Bash-Cookbook

To compile the code, we will use gcc and -lm (this refers to libmath) as follows:

$ gcc -Wall -02 -o mhelper main.c -lmath

If the compiler completes successfully (which it should), you will be left with a utility binary called mhelper (or math helper). We can also add this to our list of local commands by copying it to /bin using sudo and cp:

$ sudo cp mhelper /bin; sudo chmod a+x /bin/mhelper;

Now, mhelper can be used for basic operations such as division, multiplication, addition, and subtraction:

$ mhelper "var1" "-" "var2"
The mhelper code is not designed to be particularly robust and to handle specific edge cases, but rather to demonstrate that another utility can be used. Python and numpy would be an excellent alternatives!
主站蜘蛛池模板: 永德县| 阿拉尔市| 松阳县| 上蔡县| 江油市| 新宁县| 闻喜县| 峨边| 蓝山县| 高邑县| 剑川县| 通化县| 公安县| 商都县| 哈尔滨市| 丰原市| 顺昌县| 屯昌县| 韩城市| 哈巴河县| 辽阳县| 阳东县| 霍城县| 大化| 岚皋县| 大名县| 建平县| 井陉县| 双江| 瑞昌市| 法库县| 高碑店市| 吐鲁番市| 南宁市| 根河市| 循化| 石泉县| 宣城市| 长白| 罗山县| 清苑县|