Youda's blog

努力工作 认真生活......

0%

Linux定时任务 command not found

现象: 定时任务命令手动执行成功,但是定时执行失败,详情如下:

定时任务配置:crontab -e

1
30 * * * * cd /users/youda/xxx && sh deploy.sh > auto_deploy.log 2>&1

deploy.sh 内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
#!/bin/bash
set -u
set -e

export LANG='en_US.UTF-8'
env

cd xxxxxx

hexo clean
hexo generate

exit 0

手动执行成功

自动执行失败,auto_deploy.log 错误显示如下:

1
-bash: hexo: command not found 

原因

定时任务执行的时候不是以当前用户去执行的,当前用户配置的一些命令无法找到,所以会执行失败

解决办法

在执行脚本的前方加载用户的环境变量配置:source ~/.bash_profile
修改后的脚本文件如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/bin/bash
set -u
set -e

# 增加这么一条命令
source ~/.bash_profile

export LANG='en_US.UTF-8'
env

cd xxxxxx

hexo clean
hexo generate

exit 0