crontab cannot read environment variables normally [solved]

Prerequisite environment:

Recently, the company redis problem, decided to write a script to automatically restore:

1. When it is judged that there are less than 6 redis processes: restart the service and create a cluster, and automatically refresh the cache

2. Determine the number of clusters in redis, and automatically create clusters when there are less than 6 instances

Script and crontab:

screenplay

vi create_cluster.sh

echo yes| /usr/local/redis-3.2.1/src/redis-trib.rb create --replicas 1 192.168.200.94:7001 192.168.200.94:7002 192.168.200.94:7003 192.168.200.94:7004 192.168.200.94:7005 192.168.200.94:7006

crontab content

*/1 * * * * /usr/local/redis-3.2.1/cluster-conf/auto_Analysis_Recovery_redis_and_load_cache.sh >> /usr/local/redis-3.2.1/cluster-conf/Recovery_redis_and_load_cache-$(date +\%Y\%m\%d).log 2>&1 &

Problems and solutions

It is normal to execute the script manually, but an error is reported in crontab:

/usr/share/rubygems/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- redis (LoadError)
    from /usr/share/rubygems/rubygems/core_ext/kernel_require.rb:55:in `require'   
     from /usr/local/redis-3.2.1/src/redis-trib.rb:25:in `<main>'

The answers on the Internet are all to be installed gem insall redis; check by yourself to confirm that it has been installed and the version is normal.
Manual execution means that there is no problem, which means that there is no problem with the environment. The problem is that crontab 执行时there must 丢失be some information;

crontab有一个坏毛病,就是不会默认从用户profile文件中读取环境变量参数,经常导致在手工执行某个脚本时是成功的,但是到crontab中试图让它定期执行时就是会出错.
After reading this, you will know how to modify the script. You can use the default #!/bin/sh at the head of the script, and then write these in the first part:

###################
. /etc/profile
. ~/.bash_profile
##################

The script becomes
vi create_cluster.sh

#!/bin/sh
. /etc/profile
. ~/.bash_profile
echo yes| /usr/local/redis-3.2.1/src/redis-trib.rb create --replicas 1 192.168.200.94:7001 192.168.200.94:7002 192.168.200.94:7003 192.168.200.94:7004 192.168.200.94:7005 192.168.200.94:7006

Execute crontab again to automatically create a redis cluster.

Guess you like

Origin blog.csdn.net/yy4545/article/details/105550151