在一个项目中,我使用shell脚本来访问和操作MySQL。
首先,我写了ip,port,username,密码来连接shell脚本本身的mysql,一切正常!然后,我想在配置文件中配置ip,port,username,password,但它失败了。事实上,从配置文件加载ip,端口,用户名,密码成功,但在将这些值连接到sqlurl字符串时失败。
=============================================== ==========
[代码]
IPADDRESS="127.0.0.1"
PORT=3306
USER="abc"
PASSWORD="abc123"
echo "IPADDRESS: $IPADDRESS"
echo "PORT: $PORT"
echo "USER: $USER"
echo "PASSWORD: $PASSWORD"
echo ""
SQLURL="-h$IPADDRESS -P$PORT -u$USER -p$PASSWORD"
echo "SQLURL = $SQLURL"
echo ""
[输出]
IPADDRESS: 127.0.0.1
PORT: 3306
USER: abc
PASSWORD: abc123
SQLURL = -h127.0.0.1 -P3306 -uabc -pabc123
=============================================== ==========
[配送档案] 配置文件名为config.ini,内容为:
IPADDRESS=127.0.0.1
PORT=3306
USER=abc
PASSWORD=abc123
[代码]
# method 2.1 use the function I wrote myself
# get_config_value_by_key $filename $key
function get_config_value_by_key() {
__filename=$1
__key=$2
while read line; do
key=`echo $line|awk -F '=' '{print $1}'`
value=`echo $line|awk -F '=' '{print $2}'`
if [ $key == $__key ]; then
echo $value
fi
done < $__filename
}
configfile="config.ini"
echo "configfile = $configfile"
echo ""
IPADDRESS="`get_config_value_by_key $configfile "IPADDRESS"`"
PORT=`get_config_value_by_key $configfile "PORT"`
USER="`get_config_value_by_key $configfile "USER"`"
PASSWORD="`get_config_value_by_key $configfile "PASSWORD"`"
echo "IPADDRESS: $IPADDRESS"
echo "PORT: $PORT"
echo "USER: $USER"
echo "PASSWORD: $PASSWORD"
echo ""
SQLURL="-h$IPADDRESS -P$PORT -u$USER -p$PASSWORD"
echo "SQLURL = $SQLURL"
echo ""
# method 2.2 use sed
IPADDRESS=`sed -n -e 's/^\s*IPADDRESS\s*=\s*//p' $configfile`
PORT=`sed -n -e 's/^\s*PORT\s*=\s*//p' $configfile`
USER=`sed -n -e 's/^\s*USER\s*=\s*//p' $configfile`
PASSWORD=`sed -n -e 's/^\s*PASSWORD\s*=\s*//p' $configfile`
echo "IPADDRESS: $IPADDRESS"
echo "PORT: $PORT"
echo "USER: $USER"
echo "PASSWORD: $PASSWORD"
echo ""
SQLURL="-h$IPADDRESS -P$PORT -u$USER -p$PASSWORD"
echo "SQLURL = $SQLURL"
echo ""
[输出]
configfile = config.ini
IPADDRESS: 127.0.0.1
PORT: 3306
USER: abc
PASSWORD: abc123
-pabc123-h127.0.0.1
IPADDRESS: 127.0.0.1
PORT: 3306
USER: abc
PASSWORD: abc123
-pabc123-h127.0.0.1
=============================================== ==
正确的sqlurl输出是&#34; SQLURL = -h127.0.0.1 -P3306 -uabc -pabc123&#34; 错误的sqlurl输出是&#34; -pabc123-h127.0.0.1&#34;或其他,丢失了大部分内容。
答案 0 :(得分:0)
在通常情况下,文件CR
中有DOS行结尾NL
config.ini
。在 configfile 上运行dos2unix
会有所帮助。摆脱方法2.1的CR
的另一种简单方法是在代码中设置IFS=$'\r'
。