Please enable JavaScript.
Coggle requires JavaScript to display documents.
Linux Shell Scripting
(Link book) - Coggle Diagram
Linux Shell Scripting
(Link book)
Main Concept
- Kernel
- Linux Shell
- Process
- Redirector, Pipes, Filter, ..
What's Kernel
- It manages resources of Linux OS, resource mean facilities avaiable in Linux. EG of facility: store data, print data on printer, memory, file management, ...
- Kernel decides who will use this resource, for how long and when
- It runs your programs(or setup to executed binary files)
- It memory resident portion of Linux
- It performance following task:
-- I/O management
-- Device management
-- File management
-- Memory management
Kernel là gì??
- Nó quản lý tài nguyên của Linux OS, trong đó tài nguyên là những tiện ích có sẵn trong linux. VD: thiết bị lưu trữ dữ liệu, in dữ liệu trên máy in, bộ nhớ, quản lý tệp
- Kernel quyết định ai sẽ sử dụng tài nguyên, sử dụng như thế nào, trong bao lâu và khi nào
- Nó chạy các chương trình (hoặc thiết lập để thực thi các tệp nhị phân)
- Đó là phần bộ nhớ thường trú của Linux
- Nó thực hiện các nhiệm vụ sau:
-- Quản lý vào ra
-- Quản lý Thiết bị
-- Quản lý Tệp tin
-- Quản lý Bộ nhớ
What is Linux Shell
- Description
- How to use shell
Description
- Computer understand the language of 0's & 1's, which difficult for all of us to read and write
- Shell is a special program of OS, which accept your instruction or command in English and translate it into computer native binary language
- It's enviroment provide for user interaction
- Shell is an command language interpreter that executes command read from standard input device(keyboard or mouse) or from a file.
- Classify: BASH (Bourne Again Shell); CSH (C Shell) and KSH (KornShell)
- If we are giving commands from Keyboard, it is callded Command Line Interface - CLI ( usually in-front of $ prompt)
-
Định nghĩa
- Máy tính chỉ hiểu được ngôn ngữ dưới dạng các bit nhị phân 0 hoặc 1. Điều này thì khá khó với hầu hết mng để có thể đọc và viết chúng
- Shell là một chương trình đặc biệt của HĐH, nó chấp nhận các lệnh hoặc chỉ dẫn bằng Tiếng Anh, và chuyển chúng thành ngôn ngữ máy tính dưới dạng các bit nhị phân.
- Môi trường của nó cung cấp các giao diện người dùng
- Shell là một trình thông dịch ngôn ngữ lệnh, thực thi lệnh được đọc từ thiết bị nhập tiêu chuẩn (bàn phím hoặc chuột) hoặc từ một tệp.
- Phân loại: BASH, CSH, KSH
- Nếu ta gửi lệnh từ bàn phím, nó được gọi là Giao diện dòng lệnh (thường đứng trước dấu nhắc $)
-
What is Process
Description
- Process is any kind of program taks carried out by your PC.
- A process is program (command given by user) to perform some job.
- In Linux, when you start process, it give a number (call PID or process-ID). PID start from 0 to 65535
How to use
- Linux is multi user, multitaking os. It means you can run more than two process simultameously if you wish
- We can run command in background by the ampersand (&) at the end of command
- An instance of running command is called process and the number printed by shell is call process id (PID), this PID can be use to refer specific running process
-
Redirection of standard I/O
Description about Redirector
- Mostly all command gives output on screen or take input from keyboard, but in Linux it's possible to send output to file or read input from file
-
Pipes
Description about Pipes
- A Pipe is a way to connect the output of one program to the input of another program without any temporary file
Output of 1st cmd -> -> take input from 1st cmd for this command
- A pipe is nothing but a temporary storage place where the output of one command is stored and then passed as the input for second command.
- Pipes are used to run more than two command ( multiple commands) from same command line
- Syntax : command1 | command2
Filter
Description
- A filter performs some kind of process on the input and give the output
- Example: $ tail +20 < hotel.txt | head -n30 >hlist : print contains from line number 20 to line number 30 and store the result to file call 'hlist"
Shell Programming
- Description
- Variable
- Shell Script
- Condition
- Discard the output
Description
- Shell program is series of Linux Command
- Shell script can take input from user, file and output them on screen.
- Useful to create our own command that can save our lots of time and to automate some task of day
Variable
- Type of variable
- How to define User define varibable
- Rule for naming variable name
- Print or access value of UDV
What is variable
- Data/Info must be kept in RAM memory. RAM is devided into small locations, and each location had unique number call Memory location/address, which is used to hold our data. Programmer can give a unique name to this memory address called memory variable or variable
Type of variable
- System Variable: Created and maintained by Linux itself. Define in CAPITAL LETTERS
- User Defined Variables - UDV : Created and maintained by user. Define in lower letter
Define User Defined Variable - UDV
- Syntax: variablename=value
- E.g: $no=10
Rule for naming Variable name
- Name must begin with Alphanumeric character or underscore character (_), followed by one ore more Alphanumeric
- Don't put spaces on either side of the equal sign when assigning value for variable
- No Error: $ no=10
- Error: $no =10; $ no= 10; $ no = 10
- Variable are case-sensitive (phân biệt hoa thường), just like filename in Linux
- Can define NULL variable as follows:
- $vech=
- $vech=""
- Do not use ?, * etc to name your varibale names
Print or Access value of UDV
- Syntax : $variablename
--> $echo $vairibalename
- Operator:
- +: Additon
- -: Subraction
- / : Division
- % : Modular
- *: Multiplication
Local & Global Shell Variable
- Normally all variables are local. Local variable can be use in the same shell. If you load other copy of shell then new shell ignored all old shell's variable
- We can copy old shell's variable to new shell. such variable is know as Global Shell variable.
- Syntax:
export variable1, variable2, ..., variableN
- Example:
$vech=Bus
$echo $vech
--> Print Bus
$export vech
$/bin/bash
$echo $vech
--> Print Bus
$exit
$echo $vech
--> Print Bus
Shell script
- Write shell script
- Run shell script
- Shell Arithmetic
Write Shell script
- Using Linux's text Editor: vi, mcedit or cat
Run Shell script
- Step1: Use chmod command to give execution permission
- Syntax: chmod +x shell-script-name
- Or syntax: chmod 777 shell-script-name
- Step 2: Run Script as
- Syntax1: ./shell-script-name
- Syntax2: bash shell-script-name
- Syntax3: /bin/sh shell-script-name
Command Related with Shell Programing
- echo
- Qoutes
- "Double qoutes" : Anything enclose in double qoutes removed meaning of that characters ( except \ & $)
- 'Single quotes' : Enclosed in single quotes remain unchanged
- `Back quotes` : To execute command
Shell Arithmetic - Số học trong Shell
- $ expr 1 + 3 # print 4
- $ expr 2 - 1 # print 1
- $ expr 10 / 2 # print 5
- $ expr 20 % 3 # print 2
- $ expr 10 * 3 # print 30; multiplication use * not * sinc its wild card
- $echo `expr 6 + 3` # print 9
- $echo "expr 6 + 3" # print expr 6 + 3
Codition
- Shell Array
- If ..else
- For loop
- While loop
- Case statement
- Read statement
Shell Array
- Define Array:
- Access Array value:
- Access all the items in an array :
- ${array_name[*]}
- ${array_name[@]}
If .. else
- The if ... else...fi statement is netx form of control statement that allow Shell to execute satement in a controlled way and make the right choice
- Syntax:
if [expression]
then
Statements to be executed if expression is true
else
Statements to be executed if expression is not true
fi
- Example
#!/bin/sh
a=10
b=20
if [ $a == $b]
then
echo "a is equal to b"
else
echo "a is not equal to b"
fi
Shell loop
- The infinite loop : All the loops have a limited life and they come out once the condition is false or true depending on the loop
#!/bin/sh
a=10
until [$a -lt 10]
do
echo $a
a=`expr $a + 1`
done
- The Break statement: is used to terminate the execution of the entire loop, after completing the execution of all the lines of code upto the break statement
#!/bin/sh
a=10
until [$a -lt 10]
do
echo $a
if [$a -eq 5]
then
break
fi
a=`expr $a + 1`
done
- The Continues statement: is smilar to the break command, except that it causes the current iteration of the loop to exit rather than the entire loop
#!/bin/sh
NUMS="1 2 3 4 5 6 7"
for NUM in $NUMS
do
Q=`expr $NUM % 2`
if [ $Q -eq 0]
then
echo "Number is an even number!!"
continue
fi
echo "Found odd number"
done
Case Statement
- Case statement is good alternative to Multilevel If-then-else-fi satement. It enable you to match several value againts one variable.
- Syntax:
case $variable-name in
pattern1) command
...
...
command;;
pattern2) command
...
....
command;;
patternN) command
...
...
command;;
*) command
...
...
command;;
esac
- Example
case $rental in
"car") echo "For $rental Rs.20 per k/m";;
"van") echo "For $rental Rs.10 per k/m";;
"jeep") echo "For $rental Rs.5 per k/m";;
"bicycle") echo "For $rental 20 paisa per k/m";;
*) echo "Sory, I can not gat a $rental for you";;
esac
-
Create new shell in memory
Function in Shell
- Create Function
- Pass parameter to function
- Return value from function
- Nested function
- Function call
-
Pass parameter to function
Return value from function
- If you execute an exit command from inside a function, its effect is not only to terminate execution of the function but also of the shell program that called the function
- If you instead want to just terminate execution of the function, then there is way to come out of a defined function
- Base on the situation, you can return any value from your function using return command whose syntax is as follow:
return code
- Example
#!/bin/sh
# Define your function
Hello () {
echo "Hello World $1 $2"
return 10
}
# Invoke your function
Hello Zara Ali
# Capture value return by last command
ret=$?
echo "Return value is $ret"
- Result after executed:
$./tesh.sh
Hello Word Zara Ali
Return value is 10
Nested Function
- One of the more interesting features of functions is that they can call themselves and also other functions. A function that calls itself is as a recursive function
- Example
#!/bin/sh
# Calling one function from another
number_one() {
echo "This is the first function..."
number_two
}
number_two() {
echo "This is now the second function ...."
}
# Calling function one
number_one
- Result After executed:
This is the first function ...
This is now the second function...
Function call from prompt