function log() { local level="$1" local message="$2" local current_date=$(date +"%Y-%m-%d %H:%M:%S") if [ "$1" = "ERROR" ]; then echo -e "\e[31m[$current_date] [$level] $message\e[0m" elif [ "$1" = "DEBUG" ]; then echo "[$current_date] [$level] $message" }
function check_host() { local ip='192.168.1.1' local hostname='aaa' if grep -q "${ip}[[:space:]]*${hostname}" "/etc/hosts"; then log "WARNING" "记录已存在" else echo "${ip} ${hostname}" | tee -a "/etc/hosts" > /dev/null fi }
.bash_profile中添加记录
判断.bash_profile中是否存在环境变量如果不存在则添加
function check_profile() { local bash_profile="~/.bash_profile" if [ -f "${bash_profile}" ]; then #获取当前path值 current_path=$(grep -o 'PATH=.*' "${bash_profile}" | cut -d '=' -f2) DB_PATH="/home/db/bin" #检查DB_PATH是否在PATH中 if [[ ":${current_path}:" != *":${DB_PATH}:"* ]]; then # 添加DB_PATH到PATH new_path="${current_path}:${DB_PATH}" # 更新bash_profile sed -i "s|PATH=.*|PATH=${new_path}" "${bash_profile}" fi fi }
添加内核参数
通过读取配置文件中的内核参数,如果/etc/sysctl.conf中存在则不添加否则添加记录
function set_sysctl() { local param_file="/tmp/sysctl.conf" #检查内核参数是否存在 while IFS= read -r line; do if grep -q "${line}" "/etc/syslog.conf"; then log "WARNING" "记录已存在无需添加" else echo "${line}" | sudo tee -a /etc/syslog.conf > /dev/null log "DEBUG" "内核参数 ${line} 已经添加到 /etc/sysctl.conf" fi done < "${param_file}" }