Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình Bash

Làm chủ Simple Shell Scripts trong Linux: Hướng dẫn Bước Bước

Tạo shell scripts là một trong những essential skills Linux users nên có ở ngón tay. Shell scripts đóng vai trò enormous trong automate repetitive tasks mà nếu không thì tedious executing line by line.

Trong tutorial này, highlight basic shell scripting operations mọi Linux user nên có.

1. Tạo Simple Shell Script

Shell script là file chứa text ASCII. Bắt đầu tạo simple shell script, dùng text editor. Nhiều text editors, command-line và GUI-based. Hướng dẫn này dùng vim editor.

Tạo script đơn giản hiển thị "Hello world" khi executed.

$ vim hello.sh

Paste content sau vào file và save.

#!/bin/bash
# Print Hello world message
echo "Hello World!"

Phân tích script line by line.

  • Dòng 1 - #!/bin/bash - gọi là shebang header. Special construct chỉ ra program nào interpret script. Case này là bash shell chỉ bởi /bin/bash. Ngôn ngữ khác: Python #!/usr/bin/python3, Perl #!/usr/bin/perl.
  • Dòng 2 là comment. Comment describe script làm gì, không executed khi run. Comments luôn preceded by hash sign #.
  • Dòng cuối là command in 'Hello World' message ra terminal.

Bước tiếp: make script executable assign execute permission dùng chmod command.

$ chmod +x hello.sh

Cuối cùng, run shell script dùng một trong commands:

$ bash hello.sh
HOẶC
$ ./hello.sh
Làm chủ Simple Shell Scripts trong Linux: Hướng dẫn Bước Bước

2. Dùng Conditional Statements Execute Code

Giống ngôn ngữ khác, conditional statements trong bash scripting dùng để make decisions, slight syntax variation. Cover if, if-else, và elif.

Ví dụ if Statement Only

If statement test single hoặc multiple conditions. Bắt đầu fundamental use test single condition. If statement defined by if ... fi blocks.

if command
then
  statement
fi

Xem shell script dưới:

#!/bin/bash
echo 'Enter the score'
read x
if [[ $x == 70 ]]; then
  echo 'Good job!'
fi

Script prompt user nhập score store trong variable x. Nếu score = 70, output "Good job!". Comparison operator == test score stored in x equivalent to 100 (typo trong original: 70 vs 100).

Làm chủ Simple Shell Scripts trong Linux: Hướng dẫn Bước Bước

Comparison operators khác:

  • -eq - Equal to
  • -ne - Not equal to
  • -lt - Less than
  • -le - Less than or equal to
  • -gt - Greater than
  • -ge - Greater than or equal to

Ví dụ: if-statement block in 'Work Harder' nếu input score 50.

if [[ $x -lt 50 ]]; then
  echo 'Work Harder!'
fi
Làm chủ Simple Shell Scripts trong Linux: Hướng dẫn Bước Bước

Ví dụ if-else Statement

Situations 2 possible outcomes: whether this or that, if-else handy.

if command
then
  statement1
else
  statement2
fi

Script đọc input score check greater than or equal 70.

Score >= 70 -> 'Great job, You passed!'. Score < 70 -> 'You failed'.

#!/bin/bash
echo 'Enter the score'
read x
if [[ $x -ge 70 ]]; then
  echo 'Great job, You passed!'
else
  echo 'You failed'
fi
Làm chủ Simple Shell Scripts trong Linux: Hướng dẫn Bước Bước

Ví dụ if-elif-else Statement

Scenarios multiple conditions different outcomes, dùng if-elif-else.

if condition1
then
  statement1
elif condition2
then
  statement2
else
  statement3
fi

Ví dụ: script lottery check number entered là 90, 60 hoặc 30.

#!/bin/bash
echo 'Enter the score'
read x
if [[ $x -eq 90 ]]; then
  echo "You have won the First Prize"
elif [[ $x -eq 60 ]]; then
  echo "You have won the Second Prize"
elif [[ $x -eq 30 ]]; then
  echo "You have won the Second Prize"
else
  echo "Please try again"
fi
Làm chủ Simple Shell Scripts trong Linux: Hướng dẫn Bước Bước

3. Dùng If Statement với AND Logic

Dùng if statement cùng AND logic operator execute task nếu 2 conditions satisfied. && operator denote AND logic.

#!/bin/bash
echo 'Please Enter your user_id'
read user_id
echo 'Please Enter your tag_no'
read tag_id
if [[ ($user_id == "tecmint" && $tag_id -eq 3990) ]]; then
  echo "Login successful"
else
  echo "Login failure"
fi

5. Dùng If Statement với OR Logic

Khi dùng OR logic, represented by || symbol, either condition satisfied script give expected results.

#!/bin/bash
echo 'Please enter a random number'
read number
if [[ (number -eq 55 || number -eq 80) ]]; then
  echo 'Congratulations! You've won'
else
  echo 'Sorry, try again'
fi
Làm chủ Simple Shell Scripts trong Linux: Hướng dẫn Bước Bước

Sử dụng Looping Constructs

Bash loops cho phép users perform series tasks cho đến certain result achieved. Handy performing repetitive tasks. Section này peek at loops cũng tìm thấy trong other languages.

While loop

Easiest loops work with. Syntax simple:

while 
do
  commands
done

While loop dưới list all numbers 1 to 10 khi executed.

#!/bin/bash
# A simple while loop
counter=1
while [ $counter -le 10 ]
do
  echo $counter
  ((counter++))
done

Thảo luận while loop:

Variable counter initialized to 1. While variable <= 10, value counter incremented cho đến condition satisfied. Line echo $counter in tất cả numbers 1 to 10.

Làm chủ Simple Shell Scripts trong Linux: Hướng dẫn Bước Bước

For loop

Giống while loop, for loop execute code iteratively. I.e. repeat code execution nhiều times defined by user.

Syntax:

for var in 1 2 3 4 5 N
do
  command1
  command2
done

For loop dưới iterate 1 through 10 process values on screen.

Làm chủ Simple Shell Scripts trong Linux: Hướng dẫn Bước Bước

Cách tốt hơn achieve this: define range dùng double curly braces { } thay vì type all numbers.

#!/bin/bash
# Specify range in a for loop
for num in {1..10}
do
  echo $num
done

Bash Positional Parameters

Positional parameter là special variable referenced in script khi values passed on shell nhưng cannot be assigned. Positional parameters chạy từ $0 $1 $2 $3 ... đến $9. Beyond $9, parameters enclosed in curly brackets e.g ${10}, ${11} ...

Khi execute script, first positional parameter $0 lấy name của shell script. $1 parameter lấy first variable passed on terminal, $2 second, $3 third, etc.

Tạo script test.sh như dưới.

#!/bin/bash
echo "The name of the script is: " $0
echo "My first name is: " $1
echo "My second name is: " $2

Execute script provide first và second name as arguments:

# bash test.sh James Kiarie
Làm chủ Simple Shell Scripts trong Linux: Hướng dẫn Bước Bước

Output: first variable printed là name shell script (test.sh). Thereafter, names printed corresponding positional parameters defined.

Positional parameters useful customize data entered thay vì explicitly assign value to variable.

Shell Command Exit Codes

Trả lời câu hỏi: What is exit code?

Mọi command executed on shell bởi user hoặc shell script có exit status. Exit status là integer.

Exit status 0 = command executed successfully without errors. 1 to 255 = command failed hoặc không execute successfully.

Tìm exit status command, dùng $? Shell variable.

  • Exit status 1 = general error hoặc impermissible errors (edit files without sudo).
  • Exit status 2 = incorrect usage command hoặc builtin shell variable.
  • Exit status 127 = illegal command thường yield 'command not found' error.
Làm chủ Simple Shell Scripts trong Linux: Hướng dẫn Bước Bước

Processing Output của Shell Commands trong Script

Trong bash scripting, store output của command trong variable cho future use. Còn gọi là shell command substitution, achieve cách sau:

variable=$(command)
HOẶC
variable=$(/path/to/command)
HOẶC
variable=$(command argument 1 argument 2 ...)

Ví dụ: store date command trong variable today call shell script reveal current date.

#!/bin/bash
today=$(date)
echo "Today is $today"
Làm chủ Simple Shell Scripts trong Linux: Hướng dẫn Bước Bước

Ví dụ khác: find valid login users trên Linux system. List all users (system, process, login users) stored in /etc/passwd file.

View file dùng cat command. Narrow down login users, dùng grep search users với attribute /bin/bash và cut -c 1-10 display first 10 characters names.

Store cat command vào login_users variable.

#!/bin/bash
login_users=$(cat /etc/passwd | grep /bin/bash | cut -c 1-10)
echo 'This is the list of login users:'
echo $login_users
Làm chủ Simple Shell Scripts trong Linux: Hướng dẫn Bước Bước

Kết thúc tutorial tạo simple shell scripts. Hy vọng bạn thấy valuable.