shell脚本中[0: command not found
在写 Redis 主从复制和哨兵模式部署脚本时,代码执行报错。
代码如下:
if [$REDIS_SENTINEL_ENABLE -eq 1]; then
cp /etc/redis-sentinel.conf /etc/redis-sentinel.conf.backup
sed -i "s/^port.*/port ${REDIS_SENTINEL_PORT}/g" /etc/redis-sentinel.conf
sed -i "s/^sentinel monitor.*/sentinel monitor mymaster ${REDIS_MASTER_IP} ${REDIS_MASTER_PORT} ${REDIS_SLAVE_NUM}/g" /etc/redis-sentinel.conf
if [ `grep "^sentinel auth-pass mymaster" /etc/redis-sentinel.conf |wc -l` -eq 0 ]; then
sed -i "/^sentinel monitor mymaster/asentinel auth-pass mymaster ${REDIS_PASSWD}" /etc/redis-sentinel.conf
else
sed -i "s/^sentinel auth-pass mymaster/#sentinel auth-pass mymaster/g" /etc/redis-sentinel.conf
sed -i "/^sentinel monitor mymaster/asentinel auth-pass mymaster ${REDIS_PASSWD}" /etc/redis-sentinel.conf
fi
# redis-sentinel /etc/redis-sentinel.conf
# service 默认使用/etc/redis-sentinel.conf启动
service redis-sentinel restart
if [ $? -ne 0 ];then
echo "redis-sentinel restart failed!"
return 1
fi
fi
错误:
line 2: [0: command not found
看到错误时有点奇怪,这个是什么错误? 看一下报错的行数,感觉没写错啊,为什么执行不了,然后笔者问一下组长,才发现 if
判断少了空格。
if [$REDIS_SENTINEL_ENABLE -eq 1]; then
应该写成
if [ $REDIS_SENTINEL_ENABLE -eq 1 ]; then
结论
在if
判断中[]
这个符号有特殊要求。里面与代码之间要有空格隔开的。