1.程序shell脚本的内容大致如下:
#! /bin/bash
#execute all scripts in specified directory
MYDATE=`date +%Y%m%d%H%M%S`
SQL_PATHS=(目录1 目录2 目录3 目录4) #按文件夹执行顺序写入脚本文件夹路径,根路径为当前shell脚本路径
LOG_FILE=${MYDATE}.log
LOG_FILE1=test.log
host=******
port=3306
user=root
confirm=
password=******
function read_dir() {
count=0
echo -e "=======================sql files in directory of $1 will be executed below=======================" >>${LOG_FILE}
echo "=======================sql files in directory of $1 will be executed below======================="
for file in `ls $1`
do
if [ -d $1"/"$file ]
then
read_dir $1"/"$file
else
let count++
echo $count $1"/"$file
echo -e $count $1"/"$file >>${LOG_FILE}
fi
done
echo "=======================sql files in directory of $1 will be executed above======================="
echo -e "=======================sql files in directory of $1 will be executed above=======================\n" >>${LOG_FILE}
}
function exec_sql() {
for file in `ls $1`
do
if [ $file != "sys_data_pb_mix.sql" ]
then
if [ -d $1"/"$file ]
then
exec_sql $1"/"$file
else
mysql -h$host -P$port -u$user -p$password database_name --default-character-set=utf8 < $1"/"$file >& error.log
echo "=======================executed result in $1"/"$file======================="
echo -e "=======================executed result in $1"/"$file=======================" >>${LOG_FILE}
cat error.log >>${LOG_FILE} #输出执行日志
error=`grep ERROR error.log` #读取错误日志信息
if [ -n "$error" ] ;
then #如果有错误就退出程序
echo $error
exit
fi
fi
fi
done
echo "=======================sql files in directory of $1 has been executed success===================="
echo -e "=======================sql files in directory of $1 has been executed success====================" >>${LOG_FILE}
}
for path in ${SQL_PATHS[@]}
do
read_dir $path
done
echo "sql files will be executed on MySql:" $host "-P" $port " in database database_name with" $user
for path in ${SQL_PATHS[@]}
do
exec_sql $path
done
exit
;;
esac
2.在window下一切正常,但是到了linux环境下就直接报错了 ,类似“\r” command not found这种,具体的说明见这里:
https://cloud.tencent.com/developer/article/1068665
查资料的时候首先发现的是“dos2unix”命令的转换,但是发现centos7上并没有这个命令,查看了下安装方法,比较繁琐,发现有替代命令,果断启用dos2unix.
这是上边帖子中的描述:
当然,如果只是要转换格式,我们还有多种替代方案,没必要吊死在 dos2unix/unix2dos 上。毕竟有些系统可能没有这 2 个命令。
替代命令①:sed
以下2种都可以:
sed -e 's/.$//g' oldfile > newfile
sed 's/^M//' oldfile > newfile #注意 ^M = Ctrl + v,Ctrl + m 命令组合打印出来的字符
替代命令②:tr
cat oldfile | tr -d "\r" > newfile
3.另外还有个问题,直接通过cat这种方式生成的shell脚本,默认是没有执行权限的,需要 chmod +x shell.sh来赋权限,让脚本可已执行。
网友评论