Shell scripting là phần quan trọng của process automation trong Linux. Scripting giúp viết sequence of commands trong file và execute chúng.
Điều này save time vì không phải write certain commands again và again. Perform daily tasks efficiently và even schedule chúng cho automatic execution.
Bạn cũng set certain scripts execute on startup như show particular message launching new session hoặc set environment variables.
Applications và uses của scripting numerous, let's dive in.
Bài viết bạn sẽ học:
- Bash shell là gì?
- Bash script là gì và how to identify it?
- Cách tạo first bash script và execute it.
- Basic syntax của shell scripting.
- Cách xem system's scheduled scripts.
- Cách automate scripts bằng scheduling via cron jobs.
Best way to learn là practicing. Tôi highly encourage follow along dùng Replit. Access running Linux shell trong minutes.
Giới thiệu Bash Shell
Linux command line provided by program gọi là shell. Qua các năm, shell program evolved cater various options.
Different users configured use different shells. But most users prefer stick với current default shell. Default shell cho many Linux distros là GNU Bourne-Again Shell (bash). Bash succeeded by Bourne shell (sh).
Khi first launch shell, nó dùng startup script located in .bashrc hoặc .bash_profile file cho phép customize behavior của shell.
Khi shell used interactively, display $ khi waiting for command từ user. Gọi là shell prompt.
[username@host ~]$
Nếu shell running as root, prompt changed to #. Superuser shell prompt:
[root@host ~]#
Bash very powerful simplify certain operations hard accomplish efficiently với GUI. Remember most servers không có GUI, best learn powers của command line interface (CLI).
Bash Script là gì?
Bash script là series of commands written in file. Được read và executed by bash program. Program executes line by line.
Ví dụ, navigate đến certain path, create folder và spawn process inside dùng command line.
Same sequence of steps bằng save commands trong bash script và run it. Run script any number of times.
How to Identify a Bash Script?
File extension .sh.
Theo naming conventions, bash scripts end với .sh. Tuy nhiên bash scripts run perfectly fine without sh extension.
Scripts start with a bash bang.
Scripts identified với shebang. Shebang = combination của bash # và bang ! followed the bash shell path. First line của script. Shebang tells shell execute it via bash shell. Shebang simply absolute path to bash interpreter.
Example shebang statement:
#! /bin/bash
Path của bash program có thể vary. Sẽ see later how to identify it.
Execution rights
Scripts có execution rights cho user executing them.
Execution right represented by x. Ví dụ dưới, user tôi có rwx (read, write, execute) rights cho file test_script.sh
File colour
Executable scripts appear different colour từ rest files/folders.
Trong case tôi, scripts với execution rights appear as green.
Cách tạo First Bash Script
Tạo simple script bash output Hello World.
Create file hello_world.sh
touch hello_world.sh
Tìm path đến bash shell.
which bash
Trong case tôi, path là /usr/bin/bash và include this in shebang.
Write command.
Chúng ta echo "hello world" to console.
Script look like:
#! usr/bin/bash
echo "Hello World"
Edit file hello_world.sh dùng text editor choice add above lines.
Cung cấp execution rights cho user.
Modify file permissions allow execution script dùng command:
chmod u+x hello_world.sh
chmod modifies existing rights của file cho particular user. Chúng ta add +x to user u.
Run script.
Run script các cách:
./hello_world.sh
bash hello_world.sh.
Output:
Basic Syntax của Bash Scripting
Giống any other programming language, bash scripting follows set of rules tạo programs understandable by computer. Section này study syntax của bash scripting.
Cách define variables
Define variable dùng syntax variable_name=value. Get value variable, add $ before variable.
#!/bin/bash
# A simple variable example
greeting=Hello
name=Tux
echo $greeting $name
Tux cũng là tên Linux mascot, con penguin.
Arithmetic Expressions
Operators supported by bash cho mathematical calculations:
| Operator | Usage |
|---|---|
| + | addition |
| - | subtraction |
| * | multiplication |
| / | division |
| ** | exponentiation |
| % | modulus |
Run few examples.
Numerical expressions cũng calculated và stored in variable dùng syntax:
var=$((expression))
Try example.
#!/bin/bash
var=$((3+9))
echo $var
Fractions không correctly calculated dùng above methods và truncated.
Cho decimal calculations, dùng bc command get output đến particular decimal places. bc (Bash Calculator) command line calculator support calculation up to certain decimal points.
echo "scale=2;22/7" | bc
Nơi scale defines decimal places required in output.
Cách read user input
Sometimes need gather user input và perform relevant operations.
Trong bash, take user input dùng read command.
read variable_name
Prompt user custom message, dùng -p flag.
read -p "Enter your age" variable_name
Example:
#!/bin/bash
echo "Enter a numner"
read a
echo "Enter a numner"
read b
var=$((a+b))
echo $var
Numeric Comparison logical operators
Comparison check if statements evaluate to true hoặc false. Dùng operators dưới compare two statements:
| Operation | Syntax | Explanation |
|---|---|---|
| Equality | num1 -eq num2 | is num1 equal to num2 |
| Greater than equal to | num1 -ge num2 | is num1 greater than equal to num2 |
| Greater than | num1 -gt num2 | is num1 greater than num2 |
| Less than equal to | num1 -le num2 | is num1 less than equal to num2 |
| Less than | num1 -lt num2 | is num1 less than num2 |
| Not Equal to | num1 -ne num2 | is num1 not equal to num2 |
Syntax:
if [ conditions ] then commands fi
Example: Compare two numbers find relationship:
read x
read y
if [ $x -gt $y ]
then
echo X is greater than Y
elif [ $x -lt $y ]
then
echo X is less than Y
elif [ $x -eq $y ]
then
echo X is equal to Y
fi
Output:
Conditional Statements (Decision Making)
Conditions = expressions evaluate to boolean (true hoặc false). Check conditions dùng if, if-else, if-elif-else và nested conditionals.
Structure conditional statements:
if...then...fistatementsif...then...else...fistatementsif..elif..else..fiif..then..else..if..then..fi..fi..(Nested Conditionals)
Syntax:
if [[ condition ]] then statement elif [[ condition ]]; then statement else do this by default fi
Tạo meaningful comparisons, dùng AND -a và OR -o.
Statement dưới translate to: If a greater than 40 AND b less than 6.
if [ $a -gt 40 -a $b -lt 6 ]
Example: Find triangle type by reading lengths of sides.
read a
read b
read c
if [ $a == $b -a $b == $c -a $a == $c ]
then
echo EQUILATERAL
elif [ $a == $b -o $b == $c -o $a == $c ]
then
echo ISOSCELES
else
echo SCALENE
fi
Output:
Test case #1
Test case #2
Test case #3
Looping and skipping
For loops allow execute statements specific number of times.
Looping with numbers:
Ví dụ dưới, loop iterate 5 times.
#!/bin/bash
for i in {1..5}
do
echo $i
done
Looping with strings:
Loop through strings cũng được.
#!/bin/bash
for X in cyan magenta yellow
do
echo $X
done
While loop
While loops check condition loop until condition remains true. Cần provide counter statement increment counter control loop execution.
Ví dụ dưới, (( i += 1 )) là counter statement increment value của i.
Example:
#!/bin/bash
i=1
while [[ $i -le 10 ]] ; do
echo "$i"
(( i += 1 ))
done
Reading files
Giả sử file sample_file.txt như dưới:
Read file line by line print output on screen.
#!/bin/bash
LINE=1
while read -r CURRENT_LINE
do
echo "$LINE: $CURRENT_LINE"
((LINE++))
done < "sample_file.txt"
Output:
Cách execute commands với back ticks
Nếu need include output của complex command in script, write statement inside back ticks.
Syntax:
var= ` commands `
Example: Suppose want get output list mountpoints với tmpfs in name. Craft statement: df -h | grep tmpfs.
Include in bash script, enclose in back ticks.
#!/bin/bash
var=`df -h | grep tmpfs`
echo $var
Output:
Cách get arguments cho scripts từ command line
Có thể give arguments to script on execution.
$@ represents position của parameters, starting from one.
#!/bin/bash
for x in $@
do
echo "Entered arg is $x"
done
Run like this:
./script arg1 arg2
Cách Automate Scripts bằng Scheduling via cron Jobs
Cron là job scheduling utility present in Unix-like systems. Schedule jobs execute daily, weekly, monthly hoặc specific time of day. Automation in Linux heavily relies on cron jobs.
Syntax schedule crons:
# Cron job example
* * * * * sh /path/to/script.sh
Ở đây, * represent minute(s) hour(s) day(s) month(s) weekday(s), respectively.
Examples scheduling cron jobs:
| SCHEDULE | SCHEDULED VALUE |
|---|---|
| 5 0 * 8 * | At 00:05 in August. |
| 5 4 * * 6 | At 04:05 on Sunday. |
| 0 22 * * 1-5 | At 22:00 on every day-of-week from Monday through Friday. |
Learn about cron in detail in this blog post.
Cách Check Existing Scripts trong System
Using crontab
crontab -l lists already scheduled scripts cho particular user.
Using the find command
find command helps locate files based on certain patterns. Vì most scripts end với .sh, dùng find script như:
find . -type f -name "*.sh"
Nơi,
.represents current directory. Change path accordingly.-type findicates file type we look for là text based file.*.shtells match all files ending with.sh.
Interested read about find command in detail, check my other post.
Wrapping up
Trong tutorial này learned basics của shell scripting. Looked into examples và syntax giúp write meaningful programs.
What's your favorite thing learned from tutorial? Let me know on Twitter!
Read my other posts here.
Work vector created by macrovector - www.freepik.com