Linux 定时任务不生效的问题

时间:2023-03-08 17:20:41

Linux 中定时任务不生效的问题屡见不鲜, 本质原因是: 登录式 shell & 非登录式 shell.

登录式 shell & 非登录式 shell

登录式 shell 有:

su - <username>

Login: username / password

非登录式 shell

su <username>

图形见面

脚本执行

Bash 配置文件

全局配置文件

/etc/profile

/etc/profile.d/*.sh

/etc/bashrc

用户配置文件

~/.bash_profile

~/.bashrc

profile 类文件主要用途

设定环境变量
运行命令和脚本 

bashrc 类文件主要用途
设定本地变量
定义命令别名 

shell 读取配置文件顺序

登录式 shell

/etc/profile --> /etc/profile.d --> ~/.bash_profile --> ~/.bashrc --> /etc/bashrc

非登录式 shell

~/.bashrc --> /etc/bashrc --> /etc/profile.d/*.sh

总结

由以上信息可知, 因为定时任务是 [ 非登录式 shell ], 其读取的配置文件为: ~/.bashrc --> /etc/bashrc --> /etc/profile.d/*.sh , 故而很多环境变量不会被加载, 其中包括 PATH.

我自己写定时任务脚本的时候, 会在脚本的开头写:

#!/bin/sh

export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/usr/local/zookeeper/bin:/root/bin

这是一个很不错的方法.