在CentOS上編寫LAMP(Linux, Apache, MySQL, PHP)腳本時,可以遵循以下技巧來提高腳本的效率、可讀性和可維護性:
#!/bin/bash
# 本案例安裝一個Web系統,包含初始化、數據庫Mysql安裝、Web服務器Apache安裝、PHP運行環境和Wordpress個人博客Web系統。
# Author: qingfengyun
# Since: v2.0
# Date: 2021/08/25
# Usage: ./lamp_wordpress.sh
if [[ "$(id -u)" != "0" ]]; then
echo "Error: You must be root to run this script, please use root to install LAMP"
exit 1
fi
install_dependencies() {
yum clean all
yum repolists
yum -y install wget mariadb mariadb-server php php-mysql php-gd
}
MYSQL_ROOT_PASSWORD="your_root_password"
然后在腳本中使用這個變量:
expect -c "spawn /usr/bin/mysql_secure_installation
expect \"Enter current password for root (enter for none):\"
send \"$MYSQL_ROOT_PASSWORD\r\"
expect \"Set root password?\"
send \"$MYSQL_ROOT_PASSWORD\r\"
expect \"New password:\"
send \"$MYSQL_ROOT_PASSWORD\r\"
expect \"Re-enter new password:\"
send \"$MYSQL_ROOT_PASSWORD\r\"
expect \"Remove anonymous users?\"
send \"y\r\"
expect \"Disallow root login remotely?\"
send \"n\r\"
expect \"Remove test database and access to it?\"
send \"y\r\"
expect \"Reload privilege tables now?\"
send \"y\r\"
expect eof"
install_dependencies || {
echo "Error: Failed to install dependencies."
exit 1
}
set -e
:在腳本開頭添加set -e
,這樣當腳本中的任何命令執行失敗時,腳本會立即退出。set -e
代碼格式和可讀性:使用適當的縮進和空行來提高腳本的可讀性。例如,在函數定義和邏輯塊之間添加空行。
日志記錄:在腳本中添加日志記錄功能,以便跟蹤腳本的執行過程和結果。
echo "Starting LAMP installation at $(date)" >> /var/log/lamp_installation.log
使用expect
命令:在需要交互式輸入的步驟中使用expect
命令,例如初始化MySQL數據庫。
版本控制:對腳本進行版本控制,以便跟蹤修改歷史和協作開發。
通過遵循這些技巧,你可以編寫出更加高效、可讀和可維護的CentOS LAMP腳本。