存档在 2008年10月10日

使用mysqldump进行单表备份

2008年10月10日

写了一个shell脚本 对数据库中每个表进行备份 这样可以方便的在表中进行筛选

bak_db_table.sh
————————————————————–

# bak_db_table.sh db db_host db_user db_passwd > log.txt
# by fallseir at 20081010

if [ $1 ] # 如果没有参数
then
echo database $1;
else
echo 'backup database tables to gzip files
sh bak_db_table.sh db [db_host] [db_user] [db_passwd]
'; exit;
fi

# 参数赋值
[ $1 ] && db=$1
[ $2 ] && dbh=$2
[ $3 ] && dbu=$3
[ $4 ] && dbp=$4

# 配置数据库参数
[ $dbh ] && dbh="-h"$dbh
[ $dbu ] && dbu="-u"$dbu
[ $dbp ] && dbp="-p"$dbp

#如果不存在 以db命名的目录 则创建
[ -a $db ] || mkdir $db; echo "mkdir $db"

# 获取数据库中的表列表
echo 'list=(`echo "show tables;"|mysql -h$dbh -u$dbu -p$dbp $db`)'
list=(`echo "show tables;"|mysql $dbh $dbu $dbp $db`)
# 获取表个数
tbcount=$((${#list[@]}-2))
if [ $tbcount= -2 ] # 如果表不存在 或数据库连接失败
then
  echo empty tables in $db or connent failed! ; exit 1;
fi
echo table count: $tbcount

# 对每个表进行备份 并压缩
# 使用gzip -d $file 进行解压
# 使用 mysql $database < $bakfile 进行恢复
for (( i = 1 ; i < ($tbcount+1) ; i ++ ))
do
  table=${list[$i]}
  echo back table $table
  mysqldump $dbh $dbu $dbp $db $table | gzip -c > $db/177.6.db.$db.$table.gz
# $? 前一命令的返回值, 0 为成功 1为失败 但mysqldump没有遵守这个约定
  echo back table $table $?
  sleep 10
done

shell 中使用数组 array

2008年10月10日

发现shell中的数组使用方法
fallseir — http://blog.fallseir.com/2008/10/array_in_shell/

$ arr=(123 34 3 5)
$ echo $arr // 默认获取第一个元素
> 123
$ echo ${arr[1]} // 通过下标访问
> 34
$ echo ${arr[@]} // 访问整个数组 ,@或者* 获取整个数组
> 123 34 3 5
$ echo ${#arr[@]} // 获取数组的长度(最大下标) ,#获取长度 数组中是最后一个下标
> 3
$ echo ${#arr[3]} // 获取字符串长度
> 1
$ echo ${arr[@]:1:2} // 切片方式获取一部分数组内容
> 34 3
$ echo ${arr[@]:2} // 从第二个元素开始
> 3 5
$ echo ${arr[@]::2} // 到第二个元素
> 123 34

参考 http://www.tech-recipes.com/rx/642/bash-shell-script-accessing-array-variables/

array 的模拟操作
– http://www.tech-recipes.com/rx/911/queue-and-stack-using-array/
push:
array=(”${array[@]}” $new_element)

pop:
array=(${array[@]:0:$((${#array[@]}-1))})

shift:
array=(${array[@]:1})

unshift
array=($new_element “${array[@]}”)

function del_array {
local i
for (( i = 0 ; i < ${#array[@]} ; i++ ))
do
if [ "$1" = "${array[$i]}” ] ;then
break
fi
done
del_array_index $i
}

function del_array_index {
array=(${array[@]:0:$1} ${array[@]:$(($1 + 1))})
}