在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脚本。