Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม Bash

คู่มือ Shell & Bash Scripting จาก LinuxScrew

นี่คือเคล็ดลับที่ประโยชน์ตอนเขียน shell scripts ใน Linux

Shell scripts เป็นวิธี versatile สำหรับ automate workflows ใน Linux (และ MacOS, และตอนนี้ Windows ด้วย Windows Subsystem for Linux) Shell scripting syntax และ behavior มี quirks และมี useful shortcuts ที่ช่วยลดความซับซ้อน

Bash Scripting Tips

เคล็ดลับเหล่านี้รวบรวมจากอินเทอร์เน็ต พร้อมบางอย่างของตัวเอง

Bash scripts จะรันต่อไปแม้มี error!

ทำให้ปัญหา โดยเฉพาะตอนรับ user input และทำงานกับไฟล์ ป้องกันด้วย set command

set -eu 

วางต้น script -e ออกจาก script ตอน error และ -u ออกถ้า variable ไม่ได้ set

ALWAYS ใส่ shebang

เสมอ ใส่ shebang บรรทัดแรกของ script:

#!/bin/sh 

บอกระบบว่า shell ไหนควร interpret script สำคัญสำหรับ compatibility script เขียนสำหรับ Bash อาจ behave ต่างใน Zsh แต่ shebang รับรอง interpret ด้วย shell ที่ถูกต้อง

อย่าใช้ sudo ใน script

ทำให้ ambiguous ตอนรัน script และ issues กับ pipes และ redirection เป็น security problem ด้วย ถ้าสคริปต์ต้องการ root permissions ให้ run ทั้ง script as root หรือใช้ sudo

Check ว่ารัน as root/sudo ใน script

เพิ่ม command นี้ต้น script check ว่ารันด้วย root/sudo privileges command นี้ fail script ก่อนพยายามทำอะไร แทนที่จะ fail ตอนรัน command ที่ต้อง root

# Check if running as root if ((EUID!=0 )); then printf "Please run as root" exit 1 fi 

Skip apt prompts ด้วย -y

เพิ่ม -y ท้าย apt commands skip prompt ให้ scripts รันโดยไม่ต้อง user input:

sudo apt install nano -y 

หรือ

sudo apt upgrade -y 

Quote paths!!!

Quote paths ตอนเขียน Bash scripts สำคัญพอมีบทความเล่มเต็ม解釋ทำไม

และ correct สำหรับ current working directory

CURR_DIR="$(dirname $0);" printf -- 'moving application to /opt/app.jar'; mv "${CURR_DIR}/application.jar" /opt/app.jar; 

Set default values สำหรับ variables จาก user input

ตอน prompt user input default values ตั้งได้ด้วย:

echo "Enter a value" read val val=${val:-"Default Value"} 

ถ้า variable val ว่างหลัง read ค่า default จะถูก set

Comment เยอะๆ

เพื่อ future self - อธิบายว่าทำอะไร และทำไม Clear intention ของโค้ด good sanity check และช่วย debug และ comment มากทำให้กลับมาอ่านโค้ดภายหลังง่าย

Print, Print, Print

Print ข้อมูลมากที่สุดไป console เพื่อตอน crash รู้ว่า ที่ไหน crashed Bash scripts default ไม verbose

Emit exit status

ถ้า script เจอ error ให้ exit ด้วย exit code ที่เหมาะสม เพื่อ scripts อื่นที่เรียกมัน react ได้เหมาะสม