以备份 mysql 脚本为例,如下
#!/bin/bash
# 分隔符
str="-"
# 定义分割线函数
FenGeLine() {
## 获取屏幕宽度
ScreenLen=$(stty size |awk '{print $2}')
## 标题宽度
TitleLen=$(echo -n $1 |wc -c)
#echo $TitleLen
## 左右分割线长度
LineLen=$(((${ScreenLen} - ${TitleLen})/2)) # 一半长度,标题居中。
if [ ${LineLen} -gt 0 ];then
#echo $LineLen
# 打印分割线
yes ${str} |sed ''''${LineLen}'''q' |tr -d "\n" && echo -n $1 && yes ${str} |sed ''''${LineLen}'''q' |tr -d "\n" && echo
else
echo "$1"
fi
}
# 定义短选项和长选项
SHORT_OPTS="h"
LONG_OPTS="help,host:,user:,port:,password:,db:,backfile:,"
# 解析命令行选项
PARSED_OPTS=$(getopt -o $SHORT_OPTS -l $LONG_OPTS -- "$@")
if [[ $? -ne 0 ]]; then
exit 1
fi
# 将解析结果设置为位置参数
eval set -- "$PARSED_OPTS"
# 处理选项
while true; do
case "$1" in
-h|--help)
echo "Usage: $0 [options]"
echo " -h, --help Show help"
echo " --host connect mysql ip address"
echo " --user connect mysql user"
echo " --port connect mysql port"
echo " --password connect mysql password"
echo " --db backup mysql database"
echo " --backfile backup file"
shift
exit 0
;;
--host)
host="$2"
shift 2
;;
--user)
user="$2"
shift 2
;;
--port)
port="$2"
shift 2
;;
--password)
password="$2"
shift 2
;;
--db)
db="$2"
shift 2
;;
--backfile)
backfile="$2"
shift 2
;;
--)
shift
break
;;
*)
echo "Invalid option: $1"
exit 1
;;
esac
done
host=${host:-localhost}
user=${user:-root}
port=${port:-3306}
password=${password:-123456}
backfile=${backfile:-/opt/mysql-${db}.sql}
FenGeLine "host 默认值为 localhost"
FenGeLine "user 默认值为 root"
FenGeLine "port 默认值为 3306"
FenGeLine "password 默认值为 123456"
FenGeLine "backfile 默认值为 /opt/mysql${db}.sql}"
FenGeLine "传入的 host 为 $host"
FenGeLine "传入的 user 为 $user"
FenGeLine "传入的 port 为 $port"
FenGeLine "传入的 password 为 $password"
FenGeLine "传入的 db 为 $db"
FenGeLine "传入的 backfile 为 $backfile"
if [ -z "$db" ];then
mysqldump -h$host -u$user -P$port -p$password -A > $backfile
else
mysqldump -h$host -u$user -P$port -p$password -B $db > $backfile
fi