crontab中使用环境变量的方法(手动执行shell脚本可以,在定时任务中不行)
2012-09-11 18:23
1171 查看
在crontab中如何引用已定义的环境变量
一个shell脚本 /root/test/shell/test_crontab_env.sh,内部使用了一个环境变量 TEST_CRONTAB_ENV=test_crontab_env
且TEST_CRONTAB_ENV存在于 /etc/profile 中
如:
#!/bin/bash
echo "`date +%Y-%m-%d" "%H:%M:%S` $TEST_CRONTAB_ENV" >> /tmp/test_crontab_env.file
手动执行, 运行结果:
2010-09-04 11:23:38 test_crontab_env
添加到 crontab 中如下
*/1 * * * * /root/test/shell/test_crontab_env.sh
结果:
$> cat /tmp/test_crontab_env.file
2010-09-04 11:25:01
2010-09-04 11:26:01
...
这里引用的环境变量无效了.
使环境变量在crontab中生效的方法:
1.传参的方式
crontab中
*/1 * * * * /root/test/shell/test_crontab_env.sh "test_crontab_env"
test_crontab_env.sh 中
#!/bin/bash
echo "`date +%Y-%m-%d" "%H:%M:%S` $1" >> /tmp/test_crontab_env.file
2.在该shell脚本中定义环境变量
test_crontab_env.sh 中
#!/bin/bash
TEST_CRONTAB_ENV=test_crontab_env
echo "`date +%Y-%m-%d" "%H:%M:%S` $TEST_CRONTAB_ENV" >> /tmp/test_crontab_env.file
3.在该shell脚本中加载环境变量文件
#!/bin/bash
source /etc/profile
echo "`date +%Y-%m-%d" "%H:%M:%S` $TEST_CRONTAB_ENV" >> /tmp/test_crontab_env.file
个人觉得还是第三种方法最实用
一个shell脚本 /root/test/shell/test_crontab_env.sh,内部使用了一个环境变量 TEST_CRONTAB_ENV=test_crontab_env
且TEST_CRONTAB_ENV存在于 /etc/profile 中
如:
#!/bin/bash
echo "`date +%Y-%m-%d" "%H:%M:%S` $TEST_CRONTAB_ENV" >> /tmp/test_crontab_env.file
手动执行, 运行结果:
2010-09-04 11:23:38 test_crontab_env
添加到 crontab 中如下
*/1 * * * * /root/test/shell/test_crontab_env.sh
结果:
$> cat /tmp/test_crontab_env.file
2010-09-04 11:25:01
2010-09-04 11:26:01
...
这里引用的环境变量无效了.
使环境变量在crontab中生效的方法:
1.传参的方式
crontab中
*/1 * * * * /root/test/shell/test_crontab_env.sh "test_crontab_env"
test_crontab_env.sh 中
#!/bin/bash
echo "`date +%Y-%m-%d" "%H:%M:%S` $1" >> /tmp/test_crontab_env.file
2.在该shell脚本中定义环境变量
test_crontab_env.sh 中
#!/bin/bash
TEST_CRONTAB_ENV=test_crontab_env
echo "`date +%Y-%m-%d" "%H:%M:%S` $TEST_CRONTAB_ENV" >> /tmp/test_crontab_env.file
3.在该shell脚本中加载环境变量文件
#!/bin/bash
source /etc/profile
echo "`date +%Y-%m-%d" "%H:%M:%S` $TEST_CRONTAB_ENV" >> /tmp/test_crontab_env.file
个人觉得还是第三种方法最实用
相关文章推荐
- Linux手动执行脚本可以,但是放到定时任务 crontab 中不执行
- linux直接执行shell脚本正常,使用定时任务crontab执行出错
- MySQL使用mysqldump备份数据库脚本手工执行成功 crontab定时却失败的解决方法
- 使用crontab定时任务执行sh脚本实现tomcat实时监控(监控内容为当tomcat关闭时开启tomcat)
- 使用crontab,让linux定时执行shell脚本
- 使用crontab定时执行shell脚本
- Linux中使用crontab命令定时执行shell脚本或其他Linux命令
- linux定时任务,手动执行脚本没有问题,放入定时任务不行
- 如何使用Linux的Crontab定时执行PHP脚本的方法
- 如何使用Linux的Crontab定时执行PHP脚本的方法
- 使用crontab,让linux定时执行shell脚本
- 如何使用Linux的Crontab定时执行PHP脚本的方法
- crontab的定时任务不能自动执行,但是手动执行脚本一直能成功
- Linux(7) 常用命令扩展 改变用户环境变量 (可以实现登陆就执行shell脚本)
- 在linux下定时执行PHP脚本(定时执行crontab使用方法详解)
- Python脚本在crontab定时任务中无法运行,但是对应脚本手动执行成功
- 使用crontab定时执行shell脚本
- shell脚本直接执行没有问题,crontab定时执行失败的解决方法
- 在linux下定时执行PHP脚本(定时执行crontab使用方法详解)
- 如何使用Linux的Crontab定时执行PHP脚本的方法