Raspberry Pi_Eng_20.2.3 Basics of Script Syntax


Published Book on Amazon


All of IOT Starting with the Latest Raspberry Pi from Beginner to Advanced – Volume 1
All of IOT Starting with the Latest Raspberry Pi from Beginner to Advanced – Volume 2


출판된 한글판 도서


최신 라즈베리파이(Raspberry

Pi)로 시작하는 사물인터넷(IOT)의 모든 것 – 초보에서 고급까지 (상)

최신 라즈베리파이(Raspberry

Pi)로 시작하는 사물인터넷(IOT)의 모든 것 – 초보에서 고급까지 (하)


Original Book Contents


20.2.3  Basics of Script Syntax

 

In this section, we will describe various rules and syntax for writing scripts.

 

20.2.3.1    Definition of Script

 

Script is basically a text file. Internally, the file is defined as a script, and is differentiated from a normal text file. Defining that the file is the script is the value you enter at the beginning of the line as follows.

 

#!/bin/bash       

~

~ Skip

~

 

When you write a script, always start in this format. Here, "#!" is called "shebang, meaning that when the script is executed and the shell to interpret and execute the command is to be determined, the Shell in the file path described below should be used. If you specify it as above, it means that BASH Shell in "/bin/bash" should be used to process it.

 

From now on, we will write and run a simplest script program to explain how the script is organized and how it is executed. The example we'll use here is a simple script that shows a phrase "Hello World" on the screen and ends processing.

 

Using a text editor, enter the following contents and save it in the "hello.sh" file in the "Script" directory of your Home directory.

 

#!/bin/bash

echo "Hello World"

 

At first, we execute the following command to check if the file is generated normally.

 

pi@raspberrypi ~ $ cd Script

pi@raspberrypi ~/Script $ ls  -l hello.sh

total 4

-rw-r--r-- 1 pi pi 30 Apr 29 16:43 hello.sh

 

To execute a script file, execute permission must be granted. Grant execute permission to the file as follows and check the processing result.

 

pi@raspberrypi ~/Script $ chmod +x hello.sh

pi@raspberrypi ~/Script $ ls  -l

total 4

-rwxr-xr-x 1 pi pi 30 Apr 29 16:43 hello.sh

 

Now that everything is ready, we'll run this command.

 

pi@raspberrypi ~/Script $ ./hello.sh

Hello World

 

Now, the phrase "Hello World" is displayed on the screen. In this way, we created and executed a simple but complete script. All scripts will have complex logic internally, but the basic framework can be written and executed in the same structure and format as this script.

 

 

20.2.3.2    Comment

 

The presence of a "#" symbol at the beginning of each line in script indicates that the line is simply a comment and not executed. Basically, it is used as follows.

 

# comment

 

Comments are used to write down a various important notes when writing a script. You can also comment out part of the script command statement to prevent it from running temporarily.