[Linux]-常用代码块
1.读取执行的上级目录
basepath=$(cd `dirname $0`;cd ..; pwd)
2.Sudo切换用户并执行MySQL语句
echo '密码'|sudo -u mysqladmin -S /usr/local/mysql/bin/mysql -uMySQL用户名 -pMySQL密码 -e "delete xxxx;"
3.参数读取
if [[ $# -ge 1 ]]; then opt="$1" shift case "$opt" in -help) print_msg "$helpInfo" ;; -day) targetTime=`date -d "$1" "+%Y%m%d"` train_day $targetTime ;; -daysection) beginTime=`date -d "$1" "+%Y%m%d"` endTime=`date -d "$2" "+%Y%m%d"` while [ "$beginTime" -le "$endTime" ] do train_day $beginTime beginTime=`date -d "$beginTime +1 day " +%Y%m%d` done ;; *) print_msg "train_day参数错误 $helpInfo" -err exit 1 ;; esac else targetTime=`date -d "-1 day " +%Y%m%d` print_msg "默认统计昨日->$targetTime" train_day $targetTime exit 0 fi
Shell基础库
#!/bin/bash function print_msg(){ help='print_msg 消息内容 [-err | -waring | -info]' if [[ $# -eq 1 ]]; then echo -e "\033[42m \033[01m $1 \033[0m" elif [[ $# -ge 1 ]]; then msg=$1 opt="$2" shift case "$opt" in -err) echo -e "\033[41m \033[01m $msg \033[0m" ;; -waring) echo -e "\033[43m \033[01m $msg \033[0m" ;; -info) echo -e "\033[42m \033[01m $msg \033[0m" ;; *) echo -e "\033[41m \033[01m print_msg错误: $help \033[0m" exit 1 ;; esac else echo -e "\033[41m \033[01m print_msg错误: $help \033[0m" exit 1 fi } function read_conf(){ help="read_conf 配置文件地址 配置节名" if [[ $# -eq 2 ]] ;then value=$(sed "/^$2=/!d;s/.*=//" $1) echo $value else print_msg 'read_conf参数错误:$help' -err exit 1 fi }